繁体   English   中英

为什么setTimeout代码被阻止?

[英]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.

谁可以向我解释它是如何工作的?

这是发生,因为,每当你传递一个function里面setTimeout和调用它,传递函数将被推入callBack基础上以毫秒为单位所提供的延迟队列。 callBack队列中的函数将按照它们推送的顺序逐个执行。 因此,在您的情况下,您通过运行while循环来callBack队列中存在的function的代码流。 因此,第二次test调用需要10秒才能执行。

test(); //call 1
callBack queue ---->  [function(){ while(){} }]

test(); //call 2
callBack queue ---->  [function(){ while(){} }, function(){ while(){} }]

注意:当调用堆栈中没有任何内容要执行时,回调队列将开始执行。

最佳读取, 事件循环

如果需要非阻塞实现,则必须使用异步递归替换同步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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM