I am confused by the following paragraph of the Node.js documentation.
setImmediate()
vssetTimeout()
... The order in which the timers are executed will vary depending on the context in which they are called. If both are called from within the main module, then timing will be bound by the performance of the process (which can be impacted by other applications running on the machine).
For example, if we run the following script which is not within an I/O cycle (i.e. the main module), the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process:
It proceeds to show the following example
// timeout_vs_immediate.js
setTimeout(() => {
console.log('timeout');
}, 0);
setImmediate(() => {
console.log('immediate');
});
$ node timeout_vs_immediate.js
timeout
immediate
$ node timeout_vs_immediate.js
immediate
timeout
I don't understand what makes the result non-deterministic. Since the timers
phase happens before the check
phase, shouldn't the callbacks scheduled by setTimeout
always execute before those scheduled by setImmediate
? I don't think the order of the phases in the event loop would change due to a context switch or something.
The document also states that
However, if you move the two calls within an I/O cycle, the immediate callback is always executed first:
OK, but what makes so-called "I/O cycles" different from the main module?
I know there are a lot of related questions, but all answers merely state this fact by citing the documentation, without explaining where the non-determinism comes into play, so I don't think this is a duplicate.