Understanding setImmediate()
By Flavio
Published · Updated
Tagged: Node.js
Understand how Node.js setImmediate() runs a callback in the next event loop iteration, and how it differs from setTimeout(0) and process.nextTick().
When you want to execute some piece of code asynchronously, but as soon as possible, one option is to use the setImmediate() function provided by Node.js:
setImmediate(() => {
//run something
})
Any function passed as the setImmediate() argument is a callback that’s executed in the next iteration of the event loop.
The name is a bit misleading. The callback runs in the check phase, after the current work yields.
How is setImmediate() different from setTimeout(() => {}, 0) (passing a 0ms timeout), and from process.nextTick()?
A function passed to process.nextTick() runs after the current operation ends, still before setTimeout and setImmediate. The Node.js docs now mark process.nextTick() as legacy. Use queueMicrotask() instead. I wrote about that in process.nextTick().
A setTimeout() callback with a 0ms delay is very similar to setImmediate(). In the main module, the order of the two is not guaranteed. Inside an I/O callback, setImmediate() runs first.
Let’s see that I/O case. Save this as immediate-demo.mjs and run node immediate-demo.mjs:
import { readFile } from 'node:fs'
readFile(import.meta.filename, () => {
setTimeout(() => {
console.log('timeout')
}, 0)
setImmediate(() => {
console.log('immediate')
})
})
You get:
immediate
timeout
The file callback runs in the poll phase. setImmediate() is queued for the check phase that comes right after. The zero-delay timer waits for the next timers phase, so it comes later.
If you schedule both at the top of a script, do not rely on the order.
Use setImmediate() when you just finished I/O and you want other I/O callbacks to run before your follow-up work. Prefer it over setTimeout(..., 0) for that “after this I/O” case.
There’s also a promise version if you want to await it:
import { setImmediate } from 'node:timers/promises'
await setImmediate()Want me to talk about your product? You can sponsor this site.
Related posts about node: