setImmediate() function provided by Node.js:
setImmediate() argument is a callback that’s executed in the next iteration of the event loop.
How setImmediate() differs from other scheduling methods
How is setImmediate() different from setTimeout(() => {}, 0) (passing a 0ms timeout), and from process.nextTick() and Promise.then()?
- A function passed to
process.nextTick()is going to be executed on the current iteration of the event loop, after the current operation ends. This means it will always execute beforesetTimeoutandsetImmediate. - A
setTimeout()callback with a 0ms delay is very similar tosetImmediate(). The execution order will depend on various factors, but they will both run in the next iteration of the event loop.
Queue order
Aprocess.nextTick callback is added to the process.nextTick queue. A Promise.then() callback is added to the promises microtask queue. A setTimeout and setImmediate callback is added to the macrotask queue.
The event loop executes tasks in process.nextTick queue first, and then executes the promises microtask queue, and then executes the macrotask queue.
Execution order example
Here is an example to show the order betweensetImmediate(), process.nextTick() and Promise.then():
start(), then call foo() in process.nextTick queue. After that, it will handle promises microtask queue, which prints bar and adds zoo() in process.nextTick queue at the same time. Then it will call zoo() which has just been added. In the end, the baz() in macrotask queue is called.
CommonJS vs ES Modules
The principle aforementioned holds true in CommonJS cases, but keep in mind in ES Modules (e.g.mjs files), the execution order will be different:
This is because the ES Module being loaded is wrapped as an asynchronous operation, and thus the entire script is actually already in the
promises microtask queue. So when the promise is immediately resolved, its callback is appended to the microtask queue. Node.js will attempt to clear the queue until moving to any other queue, and hence you will see it outputs bar first.