为什么总是出现下面的:
0
...
999
超时内
立即内
setImmediate 不应该在回调队列中有优先级吗?
setImmediate(()=>{
console.log('Inside the immediate');
});
setTimeout(()=> {
console.log('Inside the timeout');
}, 1);
for (let i = 0; i < 1000; i++) {
console.log(i);
}
最佳答案
GitHub 上有几个问题引用了此行为。 A comment在 these issues 之一上很好地解释了为什么会发生:
What happens with the code you mentioned is that the timer and the immediate are added, and then the libuv event loop starts. When it starts, the libuv event loop first check for timers, and if the time between when a timer was added and when the event loop starts is greater than the timer's timeout value, then that timer will fire before any immediate.
所以基本上,如果您还没有进入事件循环,您的 setTimeout
中的回调将在第一次计时时执行。否则,setImmediate
将首先执行。
作为演示,如果您将 setTimeout
和 setImmediate
包装在另一个 setTimeout
中,则 setImmediate
会被执行第一:
setTimeout(function() {
setTimeout(function() {
console.log('setTimeout executed!')
}, 0);
setImmediate(function() {
console.log('setImmediate executed!')
});
}, 20);
关于javascript - 为什么下面的代码总是在立即之前打印超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57471077/