Some great answers here detailing how they both work.
Just adding one that answers the specific question asked:
When should I use
nextTick
and when should I usesetImmediate
?
setImmediate
.The Node.js Event Loop, Timers, and process.nextTick()
doc includes the following:
We recommend developers use
setImmediate()
in all cases because it's easier to reason about (and it leads to code that's compatible with a wider variety of environments, like browser JS.)
Earlier in the doc it warns that process.nextTick
can lead to...
some bad situations because it allows you to "starve" your I/O by making recursive
process.nextTick()
calls, which prevents the event loop from reaching the poll phase.
As it turns out, process.nextTick
can even starve Promises
:
Promise.resolve().then(() => { console.log('this happens LAST'); });
process.nextTick(() => {
console.log('all of these...');
process.nextTick(() => {
console.log('...happen before...');
process.nextTick(() => {
console.log('...the Promise ever...');
process.nextTick(() => {
console.log('...has a chance to resolve');
})
})
})
})
On the other hand, setImmediate
is "easier to reason about" and avoids these types of issues:
Promise.resolve().then(() => { console.log('this happens FIRST'); });
setImmediate(() => {
console.log('this happens LAST');
})
So unless there is a specific need for the unique behavior of process.nextTick
, the recommended approach is to "use setImmediate()
in all cases".