如何通过Javascript中的setTimeout终止无尽的while循环 [英] How to terminate endless while loop via setTimeout in Javascript
问题描述
我有一段带有while循环的代码,我想通过setTimeout()停止.但这似乎是一个永无止境的循环,永远不会触发setTimeout().如果我删除while循环,超时将正确触发.请问出什么事了?
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运行单个事件循环.它不会停止在函数中间,以查看是否有任何事件(例如单击或超时)会触发另一个函数.
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.
简而言之:在while循环完成之前,它不会运行定时功能.
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);
}
这篇关于如何通过Javascript中的setTimeout终止无尽的while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!