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