javascript - 为什么下面的代码总是在立即之前打印超时?

标签 javascript node.js

为什么总是出现下面的:

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 commentthese 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 将首先执行。

作为演示,如果您将 setTimeoutsetImmediate 包装在另一个 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/

相关文章:

javascript - 对象函数 router(req, res, next) { router.handle(req, res, next); } 没有方法

node.js - 400 从 Discord API 请求 token 时出错

javascript - NodeJS - Steam API - 自动接受好友请求

javascript - 在 AngularJS 中加载部分 View 后,如何触发对 DOM 的操作?

javascript - SignalR 自定义重定向方法

javascript - Node.js 网络库 : getting complete data from 'data' event

r - 从node.js调用shell脚本

node.js - “抽象类型X必须在运行时解析为具有值的字段Query.user的对象类型

node.js - 如何使用 Telegram bot API 请求用户的实时位置?

javascript - TypeScript 中的 `const func: (num: number) => string = String;` 是什么意思?