[英]Why setTimeout code blocked?
function test(){
setTimeout(function(){
var now=new Date();
while((new Date()).getTime() < now.getTime()+5000){ }
console.log('p')
}, 0);
}
test();
test(); //it takes 10 seconds,the second test function runs after the first finished.
can somebody explain to me how it works? 谁可以向我解释它是如何工作的?
This is happening because, whenever you pass a function
inside of setTimeout
and call it, the passed function will be pushed into the callBack
queue based on the supplied delay in milliseconds. 这是发生,因为,每当你传递一个
function
里面setTimeout
和调用它,传递函数将被推入callBack
基础上以毫秒为单位所提供的延迟队列。 The functions inside of callBack queue will be executed one by one in the order they have pushed. callBack队列中的函数将按照它们推送的顺序逐个执行。 So here in your case, you are blocking the code flow of
function
which is present inside of callBack
queue, by running a while
loop. 因此,在您的情况下,您通过运行
while
循环来callBack
队列中存在的function
的代码流。 Hence the second call of test
is taking 10 seconds to execute. 因此,第二次
test
调用需要10秒才能执行。
test(); //call 1
callBack queue ----> [function(){ while(){} }]
test(); //call 2
callBack queue ----> [function(){ while(){} }, function(){ while(){} }]
Note: Call back queue will start its execution when there is nothing in the call stack to execute. 注意:当调用堆栈中没有任何内容要执行时,回调队列将开始执行。
Best read for this, Event Loop . 最佳读取, 事件循环 。
If you want a non-blocking implementation you have to replace your synchronous while
loop with asynchronous recursion: 如果需要非阻塞实现,则必须使用异步递归替换同步
while
循环:
function test(x){ setTimeout(function loop(now) { (new Date()).getTime() < now.getTime()+2000 ? setTimeout(loop, 0, now) : console.log('p', x); },0, new Date()) } test(1); test(2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.