简体   繁体   中英

break javascript execution from inside timed loop

how to break a timed loop inside a for? I tried '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'

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/

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?

as far as working of break inside for loop it works. 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. see link using setTimeout synchronously in JavaScript

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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