Zach Brantmeier
Zach Brantmeier

Reputation: 746

Javascript - Breaking Infinite Loop?

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;
    }
}

Upvotes: 1

Views: 3982

Answers (2)

user2864740
user2864740

Reputation: 61875

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.

Upvotes: 4

cybersam
cybersam

Reputation: 66989

    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.
        }
    }

Upvotes: 1

Related Questions