打破setTimeout循环

我在setTimeout循环中遇到了一些麻烦。

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相关的post,但不能算出这一个。

编辑:

让我澄清一点,当我试图完成。

我的游戏有75回合,每回合需要500毫秒左右,在这个回合中,我想检查一下是否符合条件,并且宣布玩家赢了,在玩家赢了之后,没有必要继续其余的回合。

不要设置所有这些定时器,而是用setInterval创build一个连续的定时器:

 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

你不应该使用for循环,只是一个recursion的setTimeout

  • 阅读关于recursionsetTimeout模式
  • about 500ms ,我认为它不一定非常准确
  • setInterval是有害的 ,大多数开发人员可能不知道它。

setInterval不适合这么多事情:

  • 如果发生错误,您不能停止火车。
  • 如果你需要不同的执行时间步骤。
  • 如果你需要传递链中的数据。
  • 如果你需要做一些asynchronous的事情。
  • 更糟糕的是 – SETINTERVAL不保证执行
  • 所以只有当你知道你在做什么时才使用它!

解:

 var func = function(i){ return function(){ if (i >= 75) return; console.log("turn no. " + i); if(table.game.playerWon) { console.log('Player won'); } else { setTimeout(func(++i), 500); } } } setTimeout(func(0), 500); 

如果你想检查它是如何工作的,你可以在node.js运行它:

 var winTurn = 10; var func = function(i){ return function(){ if (i >= 75) return; console.log("turn no. " + i); if(i === winTurn) { console.log('Player won'); } else { setTimeout(func(++i), 50); } } } setTimeout(func(1), 50); 

我认为会更好,你使用setInterval而不是setTimeout。

为了清楚他们两个你分配给他们一个variables,然后清除超时

 var myVar = setTimeout(func, time); var myVar2 = setInterval(func, time); clearTimeout(myVar); clearInterval(myVar2); 

这里是你应该写的东西的一个例子

 var timeouts = []; for (var i = 0; i < 75; i++) { timeouts[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 for(var k = i; k < timeouts.length; k++) { clearTimeout(timeouts[i]); } } }; }(i), 100*i); } 

另一个更简单的解决方法是在table.game.playerWon为false时仅调用setTimeout

 var timeoutFunction = function(i) { return function() { console.log("turn no. " + i); if(table.game.playerWon) { console.log('Player won'); // Game stopped } else { timeout = setTimeout(timeoutFunction(i+1), 100); } }; } var timeout = setTimeout(timeoutFunction(0), 100); 

希望能帮助到你