【问题标题】:priority between setTimeout and setImmediatesetTimeout 和 setImmediate 之间的优先级
【发布时间】:2014-04-24 12:39:09
【问题描述】:

我在节点documentation 上读到了这篇文章:

setImmediate(callback, [arg], [...])

安排在 I/O 事件回调之后和 setTimeoutsetInterval

之前“立即”执行回调

但是,我看到了相反的情况。 setTimeoutsetImmediate 之前执行。 是否有人对此行为有解释,或有关节点事件循环的任何文档?

谢谢:)

代码:

var index = 0;

function test(name) {
    console.log((index++) + " " + name);
}

setImmediate(function() {
    test("setImmediate");
})

setTimeout(function() {
    test("setTimeout");
}, 0);

process.nextTick(function() {
    test("nextTick");
})

test("directCall");

输出:

0 directCall
1 nextTick
2 setTimeout
3 setImmediate

【问题讨论】:

  • 当我运行你的代码时(在节点 v0.10.31 上)我得到:0 directCall 1 nextTick 2 setImmediate 3 setTimeout

标签: javascript node.js


【解决方案1】:

你应该检查这个github issue

事件循环循环是定时器 -> I/O -> 立即,冲洗和重复。 文档正确但不完整:它没有提到 当你还没有进入事件循环时(就像你的 例如),然后计时器首先出现 - 但仅在第一个滴答声上。 (在 掌握。使事情复杂化的是,事情的确定性稍差 在 v0.10 中。)

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2013-09-30
    • 2017-07-01
    • 1970-01-01
    • 2013-09-12
    相关资源
    最近更新 更多