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/

0

4 Answers 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?

Sign up to request clarification or add additional context in comments.

3 Comments

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.
You need to understand that setTimeout is asynchronous, that's why this does not work.
If you need to repeat an execution of a function for a number of times, you should use setInterval instead setTimeout and loops.
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

Comments

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.

Comments

0

give a name to your timeout loop.

then do this

var yourloop = ... 
clearTimeout(yourloop);

you will break your loop timeout with this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.