Home > Software design >  How to stop a stopwatch when it reaches 0 in jquery
How to stop a stopwatch when it reaches 0 in jquery

Time:12-17

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.
}

CodePudding user response:

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;
 
$('button[id=skill]').click(function (e){
    $(this).hide(1000);
    timer = setInterval(function () {
        $("#stopWatch").html(i);
        i--;
    }, 1000);
});

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

if(i==0){
  i=20
 clearInterval(timer);
}
  • Related