Stop loop when condition variable (global var) changes in javascript -
I have a problem which I can not solve is a loop in my javascript where a global variable it depends on. Loop looping starts and when I change the value of that global variable, it never ceases.
stop = false; Var i = 0; While ((stop == incorrect) & amp; amp; (i & lt; 100000)) {console.log ("hi -" + i); I ++; } while the loop is running, if I stop = true, then it never stops
thanks!
JavaScript is inherently Is single threaded from. Once a block of code has started, it will be completed before anything happens. IE, in which case you are setting the stop to true , will not be executed until the loop is finished. You need to split your loop sections and allow individual events to run each section individually:
stop = false ; Var i = 0; Function loopologic () {var tempStop = I + 500; While (i & lt; tempStop) {// Basic processing logic console.log ("hi-" + i); I ++; } If (! Stop & amp; i & lt; 100000) window.setTimeout (Loopologic, 0); } Window.setTimeout (Loopologic, 0); This function breaks into several sections of 500 at a time. 0 continuates the setTimeout function (almost) immediately, but the next part will be placed below the execution chain. This allows other events to happen and therefore to allow this approach to update stop to true Will be.
The other way is available in compliant browsers, but it is starting beyond the scope of this question.
Comments
Post a Comment