0

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/

user2035693
  • 193
  • 2
  • 16

4 Answers4

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?

Henrique Barcelos
  • 7,670
  • 1
  • 41
  • 66
  • well, this is just an example of what I'm doing. In reality I have 3 **for** loops and one **if** that check a condition, and if that condition is false, executes a few timed functions. – user2035693 May 19 '13 at 16:57
  • You need to understand that `setTimeout` is **asynchronous**, that's why this does not work. – Henrique Barcelos May 19 '13 at 17:05
  • If you need to repeat an execution of a function for a number of times, you should use `setInterval` instead `setTimeout` and loops. – Henrique Barcelos May 19 '13 at 17:15
1

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

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314
0

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.

rishikesh tadaka
  • 483
  • 1
  • 6
  • 18
0

give a name to your timeout loop.

then do this

var yourloop = ... 
clearTimeout(yourloop);

you will break your loop timeout with this

doniyor
  • 36,596
  • 57
  • 175
  • 260