Timer function question

Where here is the timer decrementing?

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};

Thanks,

Andrej

image

Yea thats what I thought, but it is in an if statement. Its not something that runs every timeā€¦

It is decrementing in the if statement.

if (--timer < 0) {
  timer = duration;
}

And yes it does run every time because it needs to evaluate the condition. So if the condition has an assignment it will be executed.

// or more explicitly
if ((timer = timer - 1) < 0) {
  timer = duration;
}

Yea I get it has to run every time but why does it change the actual value of timer? Wouldnt it just see if one less then timer is = to 0 and then keep the original value of timer?

--timer is the same thing as time -= 1 or timer = timer - 1. If you donā€™t want to change the value of timer then you need to not use --.

Ya I get that part, I am just confused why the if statement is changing the value of the timer globally and not just in the if statementā€¦

Because the if statement condition is if (--timer < 0), your condition explicitly decrements the value of timer.

In words, that says ā€œDecrement ā€˜timerā€™ and check if the new value of timer is less than 0. If it is, then execute this block.ā€

Oh ok, could you do

timer--

And this would be different? Because usually its something like i++ or iā€“

timer-- and --timer will have the same effect here. They both modify the value of timer.

1 Like

Just to be clear. In the code posted in the OP --time and time-- is not the same.

time-- will add -1 to the DOM before resetting and --time will go to 0 and reset.

2 Likes

Right. I usually try to avoid changing a variable as I am using it in a logical condition because of exactly this sort of easy confusion.

1 Like

I agree. There arenā€™t many places I would suggest using this type of code style.

One example that comes to mind is the ā€œkeep prompting untilā€ while loop.

let input;

while ((input = prompt('Type something')) !== 'quit') {
  console.log(input);  
}
2 Likes