0

I am new to jquery so I might be making some. obvious mistake here, but the if statement at the bottom is not running.
I am making a timer, and I want the stopwatch to stop when it reaches 0, although I don't know how to do that either.

var i = 60;
 
$('button[id=skill]').click(function (e){
$(this).hide(1000)
    setInterval(function () {
        $("#stopWatch").html(i);
        i--;
    }, 1000);
});

$("#resetButton").click(function (e) {
    i = 60;return false;
 
});
if(i==0)
{
  i=20
 //I also want the stopwatch to stop when it reaches 0, don't know how to do that though.
}
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Joshua
  • 21
  • 6
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – gre_gor Dec 18 '21 at 00:25

1 Answers1

0

You need to save the interval to a variable when you create it. Then you can clear the timer when you are done.

var i = 60;
var timer = null;
 
$('#skill').click(function() {
    $(this).hide(1000);
    timer = setInterval(function() {
        $("#stopWatch").html(i);
        i--;
        if (i === 0) {
          clearInterval(timer);
        }
    }, 1000);
});

$("#resetButton").click(function() {
    i = 60;
    return false;
});

EDIT: I've fixed a logic error since my original post. The check for i === 0 is now inside the timer where it can actually run. I just copied it from OP's original code without looking close enough. Fixed now!

Chris Barr
  • 29,851
  • 23
  • 95
  • 135