gpt4 book ai didi

javascript - setTimeout 和 setImmediate 之间的优先级

转载 作者:IT老高 更新时间:2023-10-28 23:27:11 26 4
gpt4 key购买 nike

我在 Node documentation 上读到了这个:

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

To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval

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

谢谢:)

代码:

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

最佳答案

您应该检查一下 github issue

The event loop cycle is timers -> I/O -> immediates, rinse and repeat. The documentation is correct but incomplete: it doesn't mention that when you haven't entered the event loop yet (as is the case in your example), then timers come first - but only on the first tick. (In master. To complicate matters, things work slightly less deterministic in v0.10.)

关于javascript - setTimeout 和 setImmediate 之间的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23269153/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com