user1911612 user1911612 - 3 months ago 26
Javascript Question

Javascript countdown timer logic

I'm having a bit of trouble with the logic here:

var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
seccount=seccount-1;
if (seccount < 0) {
seccount=59;
return;
}
document.getElementById("sectimer").innerHTML=seccount+ " seconds!";


When this gets down to 0, the timer stays at 0 for 2 seconds and then jumps to 58 again. I have tried a few different things in the function, such as:

function sectimer() {
seccount=seccount-1;
if (seccount <= 0) {
seccount=59;
return;
}


and

function sectimer() {
seccount=seccount-1;
if (seccount < 1) {
seccount=60;
return;
}


but everything has some variation where the timer freezes at some number for 2 seconds and then goes to the number I chose.

What am I missing?

Answer

The return is misplaced. Try this:

var seccount=60;
var seccounter=setInterval(sectimer, 1000);
function sectimer() {
    seccount--;
    if (seccount < 0) {
        seccount=59;
    }
    document.getElementById("sectimer").innerHTML=seccount+ " seconds!";
}

The return caused the function to be terminated immediately, therefor, when it enters into the condition if (seccount < 0) (in case the seccount is -1), the seccount is being updated to be 59 and then it never reaches the element update below, but terminates on return. Then, the next time it runs after a second, the seccount is drops to 58 which is clearly not lower than zero, and skips into the element update row. That's why you feel like you lost 2 seconds, because you skipped one time of element update :-)