Lelio Faieta
Lelio Faieta

Reputation: 6663

div text is not updating on javascript code

var now = new Date().getTime();
var remainingSeconds = (new Date(new Date(new Date(now + 3600000).setMinutes(1)).setSeconds(0)) - now) / 1000;
console.log(remainingSeconds);
if (remainingSeconds>=120) {
    $('#countdown').text('120');
}else{
    $('#countdown').text(remainingSeconds);
}

I use this code to calculate how many seconds there are between now and the first minute of next hour. The point is that the div text is not changing if remainingSeconds is less than 120 seconds. The script is in the document ready 'cause I only check it on page load. I've created a fiddle for this.

Upvotes: 0

Views: 117

Answers (1)

Jan
Jan

Reputation: 2853

The problem is, that remainingSeconds never gets below 60 in your code. Here is an updated version that includes a workaround/solution.

$(document).ready(function(){
    var now = new Date().getTime();
    var remainingSeconds = (new Date(new Date(new Date(now + 3600000).setMinutes(1)).setSeconds(0)) - now) / 1000;
    // --- Workaround-Begin ---
    if ( remainingSeconds >= 3600 ) {
        remainingSeconds -= 3600;
    }
    // --- Workaround-End ---
    console.log(remainingSeconds);
    if (remainingSeconds>=120) {
        $('#countdown').text('120');
    }else{
        $('#countdown').text(remainingSeconds);
    }
});

Upvotes: 2

Related Questions