1
setTimeout(() => {
    console.log("In setTimeout");
});

setImmediate(() => {
    console.log("In setImmediate");
});

Output :

enter image description here

As you can see, the first time I run the module, setImmediate's callback is executed first before setTimeout's callback but the second time I run the script, it is the other way around.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Ajay Ullal
  • 378
  • 2
  • 10
  • 2
    There's an entire section in the documentation discussing the [non-determinism of execution order](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout) between `setImmediate()` and `setTimeout()`... – Patrick Roberts Dec 28 '19 at 08:10
  • @PatrickRoberts The documentation says "If both are called from within the main module, then timing will be bound by the performance of the process". Its kinda vague. Why is it bound by the performance of the process when it is in the main module and independent of it when it is outside? – Ajay Ullal Dec 28 '19 at 08:39

1 Answers1

1

This is related to the event loop , you can find a good documentation about this at this link https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ . In short setImmediate is executed after the poll phase , setTimeout is executed during the "timers" phase so there the execution order depends on the first phase executed into your node process. If you put setTimeout and setImmediate into an I/O callback ( pending callbacks ) the setImmediate will be executed first . ( See code below that is also present into the previous link )

// timeout_vs_immediate.js

const fs = require('fs');

fs.readFile(__filename, () => {
  setTimeout(() => {
    console.log('timeout');
  }, 0);
  setImmediate(() => {
    console.log('immediate');
  });
});

enter image description here

pioardi
  • 181
  • 2
  • 7