I have a piece of code with while loop which I would like to stop by setTimeout(). But it seems like a endless loop, which never triggers setTimeout(). If I remove while loop, timeout triggers correctly. What is wrong please?
$(document).ready(function()
{
var i = 0, s = false;
setTimeout( function()
{
s = true;
console.log( "Timeuot!!!" );
console.log( "s value is " + s );
}, 1000 );
while( s === false )
{
console.log( "this is while and s is " + s );
i++;
}
console.log( "iterations: " + i );
});
JavaScript runs a single event loop. It won't stop in the middle of a function to see if there are any events (such as clicks or timeouts) that would trigger a different function.
In short: It won't run the timed function until the while loop has finished.
To do this sort of thing, you'd normally have an event driven iterator.
var i = 0, s = false; setTimeout(function() { s = true; console.log("Timeuot!!!"); console.log("s value is " + s); }, 1000); next(); function next() { if (s) { return done(); } console.log({ s, i }); i++; setTimeout(next, 0); } function done() { console.log("iterations: " + i); }
As already mentioned the while loop blocks the one and only thread. To let your example do the thing you want, replace the while loop with setInterval(function) like this:
$(document).ready(function()
{
var i = 0, s = false;
setTimeout( function()
{
s = true;
console.log( "Timeout!!!" );
console.log( "s value is " + s );
}, 1000 );
var interval = setInterval(function() {
console.log( "this is while and s is " + s );
i++;
if (s) {
clearInterval(interval);
console.log("i is " + i)
}
}, 100);
});
setTimeout不会被调用,因为while永远不会结束,因此偶数调度程序不会触发setTimeout。
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.