Reputation:
I'm trying to create a simple countdown timer. It counts down from the number entered.
However, I'm trying to clear the interval when the counter gets to 0
. At the moment it seems to acknowledge the if statement
, but not clearInterval()
.
http://jsfiddle.net/tmyie/cf3Hd/
$('.click').click(function () {
$('input').empty();
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount) + 1;
var timer = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
setInterval(timer, 500);
})
Upvotes: -1
Views: 59
Reputation: 413996
You're not saving the return value of the call to setInterval
, which is the value that needs to be passed to clearInterval
. Passing the timer handler does no good.
var timer, timerHandler = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
timer = setInterval(timerHandler, 500);
Upvotes: 1