问题描述
我在突破setTimeout循环时遇到一些麻烦。
I'm having some trouble breaking out of a setTimeout loop.
for (var i = 0; i < 75; i++) {
setTimeout(function(i) {
return function() {
console.log("turn no. " + i);
if(table.game.playerWon) {
console.log('Player won');
// I want to stop the loop now
// i = 75; didn't work
}
};
}(i), 100*i);
}
我读过100个setTimeout相关帖子,但可以不知道这个。
I've read like 100 setTimeout related posts, but can't figure this one out.
编辑:
当我尝试时,让我澄清一下完成。
Let me clarify a bit when I'm trying to accomplish.
我的游戏有75个转弯,每回合需要大约500毫秒,在那个转弯期间我想检查是否满足条件并宣布玩家赢了,之后玩家赢了就没有必要继续其余的转弯了。
My game has 75 turns, each turn should take about 500ms, during that turn I want to check if a condition is met and announce that the player won, after the player has won there is no need to continue the rest of the turns.
推荐答案
而不是设置所有这些计时器,创建一个连续计时器 setInterval
:
Instead of setting all those timers, create one continuous timer with setInterval
:
var counter = 0;
var timer = setInterval(function () {
console.log("turn no. " + counter);
if (table.game.playerWon) {
console.log('Player won');
}
if (counter >= 75 || table.game.playerWon) {
clearInterval(timer);
}
counter++;
}, 100);
如果您的转弯需要500毫秒,请更改最后 100
到 500
。
If your turns should take 500ms, change that last 100
to 500
.
这篇关于打破setTimeout循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!