Node.js › Event Loop & Non-blocking IO
How does setImmediate() differ from process.nextTick() in terms of timing and typical use cases?
IntermediateAnswer
process.nextTick() schedules a callback to run at the very end of the current operation, before the event loop proceeds to any of its formal phases -- it has the highest possible priority and is typically used for ensuring some cleanup or continuation happens immediately after the current synchronous code finishes, before any I/O. setImmediate() schedules a callback for the 'check' phase, after I/O callbacks in the current loop iteration have run -- typically used to defer a piece of work until after I/O events have had a chance to be processed, avoiding starving I/O the way excessive nextTick recursion could.
function processLargeArray(items, index = 0) {
const chunkEnd = Math.min(index + 1000, items.length);
for (let i = index; i < chunkEnd; i++) { /* process items[i] */ }
if (chunkEnd < items.length) {
setImmediate(() => processLargeArray(items, chunkEnd)); // yields to I/O between chunks
}
}Real-world example A large-array processing function uses setImmediate() to break its work into chunks, yielding control back to the event loop between chunks specifically so pending I/O (like incoming HTTP requests) gets a chance to be handled rather than being starved by continuous synchronous processing.