为什么setTimeout代码被阻止?

lx1*_*412 7 javascript asynchronous settimeout

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.
Run Code Online (Sandbox Code Playgroud)

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

Raj*_*amy 5

发生这种情况是因为,无论何时传递function内部setTimeout并调用它,传递的函数都将callBack根据提供的延迟(以毫秒为单位)推入队列.callBack队列中的函数将按照它们推送的顺序逐个执行.因此,在您的情况下,您通过运行循环来阻止队列中function存在的代码流.因此第二次调用需要10秒才能执行.callBackwhiletest

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

test(); //call 2
callBack queue ---->  [function(){ while(){} }, function(){ while(){} }]
Run Code Online (Sandbox Code Playgroud)

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

最佳读取,事件循环.