1

Is it possible to do something like this, and end a seemingly infinite loop once a condition is met? When I attempt it, it crashes my browser as an infinite loop should. Is there another way to do this or is it not possible?

var nL=true;
while(nL){
    if(/* Condition */){
        nL=true;     
        break;
    }
}
2
  • 5
    The challenge here is JavaScript is single threaded, so unless your code inside the loop can affect the condition, it will never get hit. An alternative is to use setTimeout to create an "infinite loop" that gives other bits of the system a chance to do things. Commented Apr 18, 2014 at 18:33
  • Is there anything in your loop that would cause /* Condition */ to change? Commented Apr 18, 2014 at 18:35

2 Answers 2

4

If /* Condition */ is ever true then the loop will end - as break will end the loop, irrespective of what nL is set to.

Thus the problem is /* Condition */ is never true.


Now, as Matt Greer pointed out, if the goal really is to loop infinitely (or to loop a really long time), this must be done in either small batches (such as with setTimeout) or off the current global context (such as with Web Workers) such that browser will not freeze.

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

2 Comments

Unless condition is a = !a, etc.
@djechlin The condition is not specified, my only assertion is that it is not true. (Or, alternatively, the code provided is not a representative sample of the real problem ;-)
1
    var nL=true;
    while(nL){
        if(/* Condition */){
            nL=false; // Set to false to exit loop
            break; // Don't need this, if you set nL to false.
        }
    }

3 Comments

Oh duh, sorry about the typo on my part.
If you're setting nL to false, there's no longer a reason for break; correct?
True, unless the if test is inside another inner loop. Trying to be bit more general, I guess.

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.