gpt4 book ai didi

javascript - 为什么 setTimeout 代码被阻止?

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:55 26 4
gpt4 key购买 nike

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.

谁能给我解释一下它是如何工作的?

最佳答案

发生这种情况是因为,每当您在 setTimeout 中传递一个 function 并调用它时,传递的函数将被插入 callBack根据提供的延迟(以毫秒为单位)排队。 callBack队列里面的函数会按照推送的顺序一个一个执行。因此,在您的情况下,您通过运行 while 循环来阻止 callBack 队列中存在的 function 的代码流。因此 test 的第二次调用需要 10 秒才能执行。

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

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

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

最佳读物,Event Loop .

关于javascript - 为什么 setTimeout 代码被阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39554891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com