Node.js is an event-driven, single-threaded runtime environment that can perform blocking operations in a non-blocking manner. Operations that might block a single thread are managed by different phases in the underlying event loop. You can read about the event loop here.
setImmediate allows us to directly add a callback to the event queue. If you are familiar with the event loop, the check phase is specifically used to invoke callbacks set using the
setImmediate method. Let’s see how it works:
console.log('This is the first log'); setImmediate(() => console.log('This was queued!')) console.log('This is the second log');
Much like the
process.nextTick takes a callback and adds it to a queue. However, this callback is then added to the nextTickQueue so that it will be executed as soon as the current phase ends. The loop will block until the callback is resolved completely. Therefore, taking recursive
process.nextTick calls can cause I/O starvation as the event loop might never reach that phase. Let’s see how it works:
console.log('This is the first log'); process.nextTick(() => console.log('This was queued!')) console.log('This is the second log');
process.nextTick appear to be doing the same thing; however, you may prefer one over the other depending on your callback’s urgency. It is interesting to note that
setImmediate adds callbacks to the event queue that are executed during the check phase, whereas
process.nextTick executes callbacks immediately after the current phase. This irony has also been mentioned in the official documentation, however, changing the names could break a lot of packages and applications that use these methods.
The official documentation states:
We recommend that developers use
setImmediate()in all cases because it’s easier to think about.
process.nextTick is certainly useful, it also has the potential to cause I/O starvation. With more power comes more responsibility.
View all Courses