Reputation:
I know this question has been answered before, but none of the other answers seemed to quite solve my problem. I have a timer function that, on invocation, should use setInterval to run every second for 5 seconds and then stop. This works once, but clearInterval doesn't seem to be working, since the second half of the countdown loop keeps running. I feel like this is a scope error, but I've tried moving setInterval and clearInterval outside the function with no luck. Here's my code - this function is called on a button click:
var startGame = function(){
var count = 5;
var countdownTimer = function(){
setInterval(countdown, 1000);
};
var countdown = function(){
if (count > 0){
console.log('inside counter loop');
count--;
$('.timer').text('0:' + count);
} else {
clearInterval(countdownTimer);
console.log('inside endGame loop');
//endgame(); //This should run once when the timer reaches 0.
}
};
countdownTimer();
};
Right now, the loop will run correctly once, and then console.log 'inside endGame loop' every second without resetting. I want the loop to run once, stop, and then wait to be restarted until the on click handler calls the function again.
Upvotes: 0
Views: 930
Reputation: 133403
setInterval()
returns the interval id you need to store it and use that with clearInterval()
var startGame = function() {
var count = 5;
var intervalID ;
var countdownTimer = function() {
//Store the intervalID
intervalID = setInterval(countdown, 1000);
};
var countdown = function() {
if (count > 0) {
console.log('inside counter loop');
count--;
$('.timer').text('0:' + count);
} else {
if (intervalID) {
//Pass currect pointer
clearInterval(intervalID);
}
}
};
countdownTimer();
};
Upvotes: 1