I read this on the node documentation :
setImmediate(callback, [arg], [...])
To schedule the "immediate" execution of callback after I/O events callbacks and before
setTimeout
andsetInterval
However, I see the opposite.
setTimeout
is executed before setImmediate
.
Does someone have an explenation for this behavior, or any documentation on the node event loop ?
Thanks :)
code :
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");
output :
0 directCall
1 nextTick
2 setTimeout
3 setImmediate
setImmediate() and setTimeout() are similar, but behave in different ways depending on when they are called. setImmediate() is designed to execute a script once the current poll phase completes. setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
Promises are faster than setTimeout. Resolved!
Because of the event loop priorities dequeuing jobs from the job queue (which stores the fulfilled promises' callbacks) over the tasks from the task queue (which stores timed out setTimeout() callbacks).
You should check this 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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With