在JavaScript中, setTimeout(回调,延迟)表示在延迟后调用回调 毫秒。但是如果延迟是 0 呢?它应该立即调用回调吗?
In JavaScript, setTimeout(callback, delay) means "call callback after delay milliseconds". But what if delay is 0? Should it call callback right away?
我很困惑,因为我在运行以下代码时看到的内容:
I am confused because of what I see when I run the following code:
setTimeout(function() { console.log('AAA'); }, 0); // Call this in 0 milliseconds for (i = 0; i < 1000; i++) { console.log('BBB'); } for (i = 0; i < 1000; i++) { console.log('CCC'); } for (i = 0; i < 1000; i++) { console.log('DDD'); } for (i = 0; i < 1000; i++) { console.log('EEE'); }这会将以下内容记录到控制台:
This logs the following to the console:
我希望看到 AAA 记录多少比那更早。在应该立即调用的函数之前,有时间对 console.log 执行4000次其他调用。
I expected to see AAA logged much sooner than that. There was time to execute 4000 other calls to console.log before a function which should have been called immediately.
有人可以解释当延迟设置为0毫秒时 setTimeout 正在做什么?
Can someone explain what setTimeout is doing when the delay is set to 0 milliseconds?
推荐答案一些有用的事实可能有助于澄清正在发生的事情:
A few useful facts might help clarify what's happening:
(注意:这意味着延迟在 setTimeout 中调用不是肯定的;在执行回调之前它是最小延迟。实际花费的时间取决于它的持续时间需要处理队列中前面的任何消息。)
(Note: this means the delay in a setTimeout call is not a sure thing; it is the minimum delay before the callback is executed. The actual time taken depends on how long it takes to process any messages ahead of it in the queue.)
如果延迟设置为 0 ?一条新消息立即被添加到队列中,并将在当前正在执行的代码完成并且已处理任何先前添加的消息时进行处理。
So what happens if the delay is set to 0? A new message is added to the queue immediately, and will be processed when the currently executing code is finished and any previously-added messages have been processed.
当您调用 setTimeout ...
setTimeout(function() { console.log('AAA'); }, 0);...使用指定的回调将消息添加到队列中。剩下的代码...
…a message gets added to the queue with the specified callback. The rest of your code…
for (i = 0; i < 1000; i++) { console.log('BBB'); } // etc....继续同步执行。一旦完成,事件循环将轮询消息队列以查找下一条消息,并找到具有 setTimeout 回调的回调,然后处理该回调(运行回调)。
…continues executing synchronously. Once it has completely finished, the event loop polls the message queue for the next message and finds the one with your setTimeout callback, which is then processed (the callback is run).
只有当当前正在执行的代码完成后,回调才会执行,无论需要多长时间。
The callback only ever gets executed after the currently executing code has finished, no matter how long that takes.
有关事件循环的详细信息,请参阅:
For more details on the event loop, see:
- 并发模型和事件循环 -MDN
- JavaScript事件循环:解释 -Carbon Five
- Concurrency model and event loop—MDN
- The JavaScript event loop: explained—Carbon Five
更多推荐
设置为0毫秒时setTimeout的作用是什么?
发布评论