最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to break while loop outside it - Stack Overflow

programmeradmin1浏览0评论

this is not a mon 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;
}

this is not a mon 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;
}
Share Improve this question asked Mar 30, 2013 at 7:12 ShoSho 1842 silver badges9 bronze badges 3
  • The first vertion is not garanteed to work. As javascript timer is not garanteed. But the second should work. What problem you are facing after correcting you speeling as my previous peer mentioned – user2193789 Commented Mar 30, 2013 at 7:22
  • It is not mon because it will freeze the browser. – RobG Commented Mar 30, 2013 at 7:25
  • @silentboy they not work, both freeze the browser. i wonder why the 'while' not break when the window.t = false ? – Sho Commented Mar 30, 2013 at 8:40
Add a ment  | 

4 Answers 4

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论