提问者:小点点

JavaScript中有事件循环吗? [副本]


我有一个时间间隔为0毫秒的setTimeout调用,如下面所示,setTimeout会立即执行吗?

setTimeout(() => {
    console.log('I am first.');
}, 0);

共2个答案

匿名用户

不!! 但它会尽快执行。 指定的时间量或延迟不是执行的保证时间,而是执行的最小时间。 所以一旦堆栈为空,零ms将立即执行。

匿名用户

间隔为0 ms的setTimeout不会立即执行。 要理解概念,请遵循下面的代码,

// event loop example
// setTimeouts will land in the a queue (FIFO) via WebAPI environment, which is part of the event loop
setTimeout(() => {
    console.log('I am first.');
}, 0);
setTimeout(() => {
    console.log('I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!');
}, 0);
setTimeout(() => {
    console.log('Even, I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!');
}, 0);
// JavaScript statements land in the call stack (LIFO)
console.log('I will execute first because I am in the JavaScript environment call stack!');

输出:

I will execute first because I am in the JavaScript environment call stack!
I am first.
I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!
Even, I had to wait for the other JavaScript statements and other setTimeouts with 0 ms above me, because all setTimeouts will be in a queue!

引用:超时和间隔