我知道这个问题之前已经被回答过,但其他答案似乎都没有完全解决我的问题。我有一个计时器函数,在调用时,应使用 setInterval 每秒运行 5 秒,然后停止。这有效一次,但clearInterval似乎不起作用,因为倒计时循环的后半部分仍在运行。我觉得这是一个范围错误,但我尝试将 setInterval 和clearInterval 移到函数之外,但没有成功。这是我的代码 - 单击按钮时调用此函数:
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();
};
现在,循环将正确运行一次,然后每秒 console.log 'inside endGame Loop' 而无需重置。我希望循环运行一次,停止,然后等待重新启动,直到单击处理程序再次调用该函数。
最佳答案
setInterval()
返回您需要存储它的间隔 ID 并将其与 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();
};
关于javascript - SetInterval/ClearInterval 循环无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30860535/