-1

What's wrong with my code? I can't get the timer to stop at 0. It keeps going down to negative numbers. I have my clearInterval set, why isn't the timer stopping?

var seconds = 30;

$("#timer").on("click", run);

$("#timer").on("click", show);

var timer;

function run() {

    clearInterval(timer);
    timer = setInterval(decrement, 1000);

}

function decrement() {

    seconds--;
    $("#timer").html("<h2>" +"Time Remaining: " + seconds + "</h2>");

}

// Stop function

function stop() {

    clearInterval(timer);

}

// When seconds hit zero

if (seconds === 0) {

    stop();
    alert("Time's Up!");

}
halfer
  • 19,824
  • 17
  • 99
  • 186
Jason
  • 11
  • 3

1 Answers1

1

Your problem is that your if statement is run once, but it isn't ever checked again, and then never run again. If you move the if statement into your decrement function you should be good as gold.

The function might look something like,

function decrement() {
    seconds--;    
    if (seconds === 0) {
        stop();
        alert("Time's Up!");
    }
    $("#timer").html("<h2>" +"Time Remaining: " + seconds + "</h2>");
}
tmcnicol
  • 576
  • 3
  • 14
  • This would alert `Time's Up!` one full second after the countdown reaches zero. You should probably decrement first, then test if it's zero. – Paul Oct 30 '18 at 01:41
  • Could you please clarify on that? Pardon my amateur coding skills. The alert does come up one full second before reaching zero. – Jason Oct 30 '18 at 01:54
  • Good catch @Jason – tmcnicol Oct 30 '18 at 01:59
  • @tmcnicol Would you happen to know how I can solve that? To get the timer to stop at 0 instead of one full second before 0? – Jason Oct 30 '18 at 02:03
  • This works now, but the `

    ` will still say 1 until after the alert is closed unless the line that updates the `

    ` is also moved before the if statement (but still after decrementing `seconds`).

    – Paul Oct 30 '18 at 02:28
  • @Jason what is the problem you are having, the behaviour I am seeing is that it pauses on one second and when you clear the alert it goes to one. If you move the last line of the decrement function above the if statement it will show 0 in the menu and then the alert will pop up. – tmcnicol Oct 30 '18 at 06:42
  • This is what I have now. Can I get the alert to pop up when 0 is displayed on timer? function decrement() { seconds--; $("#timer").html("

    " +"Time Remaining: " + seconds + "

    "); if (seconds === 0) { stop(); alert("Time's up!") } Apologies for the messy look, not sure how I can make that look better. I have everything above the if statement already, other than the conditions inside the if statement which is the stop function (clearInterval) and the alert.
    – Jason Oct 30 '18 at 13:25