简体   繁体   English

从定时循环内部中断javascript执行

[英]break javascript execution from inside timed loop

how to break a timed loop inside a for? 如何在for中打破定时循环? I tried 'return', 'break', 'throw'. 我试过'return','break','throw'。 Nothing seems to work. 似乎没什么用。 It just continues with the loop. 它只是继续循环。 If I try with a label I get an error: 如果我尝试使用标签,我会收到错误消息:

Uncaught SyntaxError: Undefined label 'breakout' 未捕获的SyntaxError:未定义的标签'breakout'

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/ http://jsfiddle.net/hyc8j/1/

This function has a delay of it's execution... After 2 seconds, the loop has far way executed its five iterations. 这个函数延迟执行... 2秒后,循环执行了五次迭代。 You should put the loop inside the callback function. 你应该将循环放在回调函数中。

And just to ask, what's you intention with this? 只是问一下,你对此有何意图?

as far as working of break inside for loop it works. 至于在for循环中工作,它的工作原理。 Try just below. 试试下面。 It works 有用

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

It happening because setTimeout is asynchronous function. 它发生的原因是setTimeout是异步函数。 see link using setTimeout synchronously in JavaScript 在JavaScript中查看使用setTimeout同步的链接

According to my understanding of your code and your question, I think we cannot break the timed loop and In your code if you want to break for loop just keep break statement outside the timed loop block. 根据我对你的代码和你的问题的理解,我认为我们不能打破定时循环,并且在你的代码中,如果你想要中断循环,只需在定时循环块之外保留break语句。

Please Correct me if I am wrong. 如果我错了,请纠正我。

give a name to your timeout loop. 给你的超时循环命名。

then do this 然后这样做

var yourloop = ... 
clearTimeout(yourloop);

you will break your loop timeout with this 你将用这个来打破你的循环超时

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM