Home > Back-end >  Timer reaching zero then calling a function fail
Timer reaching zero then calling a function fail

Time:04-08

I have taken this simple timer method from here.

What I want is pretty simple, yet I can’t figure it out.

When the timer reaches zero (0:00), I want a popup alert. At the same time, the timer should continue in negative time.

So everything is working, except the popup. Any idea why?

window.onload = function() {
  var minute = 0;
  var sec = 3;
  setInterval(function() {
    document.getElementById("timer").innerHTML = minute   " : "   sec;
    sec--;
    if (sec == 00) {
      minute --;
      sec = 59;
      if (minute == 0 && sec == 00) {
        alert("You failed!");
      }
    }
  }, 1000);
}
  <div   id="coutdown">
      Time remaining to find solution: <span id="timer">10 : 00</span>
    </div>

CodePudding user response:

window.onload = function() {
      var minute = 0;
      var sec = 3;
      setInterval(function() {
        document.getElementById("timer").innerHTML = minute   " : "   sec;
        sec--;
        if (sec == 00) {
    if (minute == 0 && sec == 00) {
            alert("You failed!");
          }
          minute --;
          sec = 59;
        }
      }, 1000);
    }

In your code you are checking minute and second condition after you minute-- that means -1 which is not equal to zero, call it before making minus 1

CodePudding user response:

Your conditional is checking whether sec == 0 immediately after you set sec = 59, so the conditional will never occur. Do you mean to have the order of this setter and the conditional swapped?

  • Related