Let's write the above example as follows:
var fs = require('fs') fs.readFile("readme.txt", function (){ setTimeout(function timeout() { console.log('TIMEOUT-1 FIRED'); }, 0) setTimeout(function timeout() { console.log('TIMEOUT-2 FIRED'); }, 0) setImmediate(function D() { console.log(1); }); setImmediate(function D() { console.log(2); }); setImmediate(function D() { console.log(3); }); setTimeout(function timeout() { console.log('TIMEOUT-1 FIRED'); }, 0) setTimeout(function timeout() { console.log('TIMEOUT-2 FIRED'); }, 0)})
Exit:
1 2 3 TIMEOUT-1 FIRED TIMEOUT-2 FIRED TIMEOUT-1 FIRED TIMEOUT-2 FIRED
Explanation:
The execution order of the timers will depend on the context in which they are called. If both are called from the main module, then synchronization will be related to the performance of the process (which can be affected by other applications running on the machine). For example, if we run the following script that is not in the input / output cycle (i.e., the main module), the order in which two timers are executed is non-deterministic, since it is related to the performance of the process:
// timeout_vs_immediate.js setTimeout(function timeout () { console.log('timeout'); },0); setImmediate(function immediate () { console.log('immediate'); }); $ node timeout_vs_immediate.js timeout immediate $ node timeout_vs_immediate.js immediate timeout
However, if you move two calls during an I / O cycle, the immediate callback is always executed first:
// timeout_vs_immediate.js var fs = require('fs') fs.readFile(__filename, () => { setTimeout(() => { console.log('timeout') }, 0) setImmediate(() => { console.log('immediate') }) }) $ node timeout_vs_immediate.js immediate timeout $ node timeout_vs_immediate.js immediate timeout
The main advantage of using setImmediate () over setTimeout () is that setImmediate () will always be executed before any timers if it is planned during an I / O cycle, regardless of the number of timers.
For more information, go to the following link: https://github.com/nodejs/node/blob/master/doc/topics/the-event-loop-timers-and-nexttick.md