luiyezheng luiyezheng - 6 months ago 21
jQuery Question

How to clearInterval in a if else statement?

I'm trying to make little Countdown Timer. When the user click the button, the timer begin and set

isTiming
to true, then when the user click the button again, the timer stops and set
isTiming
to false. The problem is that the
timeInterval
was not cleared when I click the button to stop the Timer. I logged the
timeInterval
and found it to be
undefined
. Where did I go wrong?

$("#time-count").click(function() {
if (!isTiming) {
isTiming = true;

$( "#minus" ).fadeOut();
$( "#plus" ).fadeOut();
$( "div#inner" ).css("animation", "loader" + " " + String(60 * Number($("#time-count").text())) + "s ease-out");
$(this).text($(this).text() + ":" + "00")

//set the timeInterval
var timeInterval = setInterval(function() {
var t = formatTimeRemaining($("#time-count").text());

if (t.sec.length === 1) {
$("#time-count").text(t.min + ":" + "0" + t.sec);
}else {
$("#time-count").text(t.min + ":" + t.sec);
}
if (t.total <= 0) {
clearInterval(timeInterval);
}
}, 1000)

}else {
isTiming = false;

//Try to clearInterval here but fail
clearInterval(timeInterval);
$("#time-count").text("20");
$( "#minus" ).fadeIn();
$( "#plus" ).fadeIn();
}
});


You can have a look at my code on CodePen

Answer

Your timeInterval needs to be global, otherwise you have a local variable every time you click.

Comments