Search code examples
javascripttimercountersetintervalcountdown

Why does the Countdown stuck at "1"?


var count=6
var counter=setInterval(timer, 1000);

function timer(){
count=count-1;
if (count === 0){
     requestAnimationFrame(repeat);
     clearInterval(counter);
     return;
}
var countdown = createEntity($('<div id="countd"><p id="countp"></p></div>'));
game.add(countdown);
document.getElementById("countp").innerHTML=count;
}

This is my approach to the Countdown. I'm coding a Game. First of all it shows a Countdown... But why does it stuck at "1"? And if I'm playing it still staying "1" over the display.

My idea was, clearInterval(Counter) but it doesn't work. Are there any other approches?


Solution

  • The problem with your code is that you:

    1. decrement the variable
    2. test if it is zero and if so you return from the loop.
    3. In all other cases you update the div tag.

    In other words: if the counter is zero you do not update the div-tag, and therefor the last displayed value is 1

    Assuming that the problem you are describing is the only problem with your code, you could change it to something like this:

    function timer() {
      var countdown = createEntity($('<div id="countd"><p id="countp"></p></div>'));
      game.add(countdown);
      count -= 1;
      document.getElementById("countp").innerHTML=count;
      if (count === 0) {
        requestAnimationFrame(repeat);
        clearInterval(counter);
      }
    }
    

    I basically just moved the if-statement to after the field is updated. I have not tested the code, but if you get the idea of what to change.

    I am however curious if you really want to call createEntity and game.add(countdown) on every timer-invocation. In most cases you want to create the tag before you call the timer-function, and just update the value. But maybe you are doing some animation and therefor need individual tags for each value, so it isn't necessarily wrong to do it that way.