gpt4 book ai didi

javascript - setTimeout 不会立即启动

转载 作者:行者123 更新时间:2023-11-30 12:53:24 25 4
gpt4 key购买 nike

当我将以下函数放在文档的头部时:

(function(){
var d = new Date().getTime();
console.log(new Date().getTime() - d);

window.setTimeout(function(){
console.log(new Date().getTime() - d)
}, 1);

window.setTimeout(function(){
console.log(new Date().getTime() - d)
}, 10);

window.setTimeout(function(){
console.log(new Date().getTime() - d)
}, 100);

window.setTimeout(function(){
console.log(new Date().getTime() - d)
}, 1000);
}());

我有这些日志:

0
401
401
402
1397

setTimeout 开始之前似乎有 400 毫秒的延迟。为什么?

最佳答案

Javascript 不是多线程的 - setTimeout 不会立即启动。当您调用 setTimeout 时发生的所有事情就是将该函数放入队列中,以便在当前执行堆栈展开时执行。在您的情况下,到达该点大约需要 400 毫秒。

参见 How Timers Work一个很好的教程。特别是,这句话是相关的:

In order to understand how the timers work internally there’s one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution.

关于javascript - setTimeout 不会立即启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179384/

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