0

如何打破for中的定时循环?我尝试了“返回”、“中断”、“投掷”。似乎没有任何效果。它只是继续循环。如果我尝试使用标签,则会出现错误:

未捕获的语法错误:未定义的标签“突破”

var r=0;
breakout:
for(i=0;i<5;i++) {
  setTimeout(function() {
    if(r) {
       alert("works");
    } else {
       throw new Error(alert("error"));
       break breakout;
    }
  }, 2000);
}

http://jsfiddle.net/hyc8j/1/

4

4 回答 4

1

This function has a delay of it's execution... After 2 seconds, the loop has far way executed its five iterations. You should put the loop inside the callback function.

And just to ask, what's you intention with this?

于 2013-05-19T16:53:41.483 回答
1

就 for 循环内部的 break 工作而言,它可以工作。试试下面。有用

for (i=0;i<10;i++)
  {
  if (i==3)
    {
  alert("Got break");
    break;
    }
  alert("did not break");
  }

这是因为 setTimeout 是异步函数。请参阅在 JavaScript 中同步使用 setTimeout 的链接

于 2013-05-19T17:02:20.210 回答
0

根据我对你的代码和你的问题的理解,我认为我们不能打破定时循环,如果你想打破 for 循环,在你的代码中只需将 break 语句保留在定时循环块之外。

如果我错了,请纠正我。

于 2013-05-19T17:02:32.497 回答
0

为您的超时循环命名。

然后这样做

var yourloop = ... 
clearTimeout(yourloop);

你会用这个打破你的循环超时

于 2013-05-19T17:04:08.040 回答