简体   繁体   中英

How to break while loop outside it

this is not a common condition, but what's the misuse of it?

var t = true;

setTimeout(function(){
    t=false;
},1000);

while(t){
    //loop...
    //if t==false, break loop.
}

another condition, it causes endless loop too:

button.onlcick = function(){
    t = false;
}

JavaScript is single-threaded; setTimeout callback won't be called when you're blocking the main event loop with that while ( while (t) { ... } ).

If you're running your code in browser, you can't really do anything about it but writing your code in other way;

Instead of blocking the main event loop, you can use Promises Pattern .

If you're running your code in something like node you can use native modules, making you able to create threads (like threads_a_gogo .)

Because the while loop never exits, your other code is never run when something is done synchronously. My best offer for you would be not to use a while loop and instead have a recurring event such as setTimeout and make the timeout run itself when complete. This way you're not creating a closed environment.

It won't work because javascript is not multithreaded - until your current thread of execution ends (and it won't as long as you're running your while loop), no other code is executed (no timeout call) and the UI is frozen (button clicks will not respond).

There might be a way to do something like that with the new Web Workers feature in html5, but as of now i'm not able to tell with certainty.

you can use labels with break condition like outer:while() { //code if() break outer; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM