简体   繁体   English

setTimeout 不会立即开始

[英]setTimeout doesn't start instantly

When I put the following function in the head of my document :当我将以下函数放在文档的头部时:

(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);
}());

I have these logs :我有这些日志:

0 0
401 401
401 401
402 402
1397 1397

There seems to be a delay of 400ms before the setTimeout starts.setTimeout开始之前似乎有 400 毫秒的延迟。 Why?为什么?

Javascript is not multi-threaded - setTimeout does not start instantly. Javascript 不是多线程的 - setTimeout不会立即启动。 All that happens when you call setTimeout is it puts that function onto a queue to be executed when the current execution stack unwinds.当您调用setTimeout时,所有发生的事情就是将该函数放入一个队列中,以便在当前执行堆栈展开时执行。 In your case, it is taking about 400 ms to get to that point.在您的情况下,达到这一点大约需要 400 毫秒。

See How Timers Work for a good tutorial on this.有关此方面的优秀教程,请参阅计时器的工作原理 In particular, this quote is relevant:特别是,这句话是相关的:

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 都在单个线程上执行,因此异步事件(例如鼠标单击和计时器)仅在执行中有一个打开时才运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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