admin管理员组文章数量:1418400
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
4 Answers
Reset to default 3JavaScript
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; }
本文标签: javascriptHow to break while loop outside itStack Overflow
版权声明:本文标题:javascript - How to break while loop outside it - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745274921a2651124.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论