9

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 and setInterval

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
Huangism
  • 16,278
  • 7
  • 48
  • 74
etnbrd
  • 471
  • 6
  • 18

1 Answers1

3

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.)

Frédéric GRATI
  • 805
  • 1
  • 6
  • 19