Process.nextTick, the event loop invader

Process.nextTick, the event loop invader
Spread the love

process.nextTick() is that tough customer that gets in a bank queue and says to the banker, attend to me after the current customer you are attending to, regardless of whether it’s my turn or not. 

Rude, right?

While trying to understand the fundamentals of Javascript & NodeJS, the event loop is usually one of the crucial concepts you’ll come across.

The event loop allows Node.js to perform non-blocking I/O operations – despite the fact that JavaScript is single-threaded — by offloading operations to the system kernel whenever possible.

Here is a simplified overview of the NodeJS event Loop order of operation

Image from Libuv

So, back to process.nextTick, in the event Loop, setInterval, setTImeout, and setImmediate are all well represented in different phases of the loop cycle but process.nextTick is not, why? NodeJS event loop uses libuv default event loop and its own native queues — NextTicks and MicroTasks queues (they are sometimes referred to as priority queues).

SetInterval, setTImeout —both in the timers phase, and setImmediate — the check handles phase —  all fall into the libuv event loop order of execution but process.nextTicks doesn’t follow that pattern. 

So, any callback passed to the process.nextTicks’s construct is processed after the current event loop phase — the phases described in the previous image. Essentially, if your code contains any process, nextTick callbacks will run first before any other callback functions.

As shown in the image below

Use `process.nextTick()` when you want to ensure your callback runs in the next event loop and when you want your callback to be executed asynchronously, not at a specific time.

However, there is a caveat; taking recursive process.nextTick calls can cause I/O starvation as all nextTicks will have to be processed before any other phase can happen. Ensure you don’t have a recursive process.nextTicks.

Here is another visual representation of how NextTIcks work with the NodeJS event loop.

Image from InsiderAttack

Have you used nextTicks recently? Any particular reason you haven’t yet? Is there something I missed?

Sign up for LeanDev NewsLetter

Published by Eze Sunday Eze

Hi, welcome to my blog. I am Software Engineer and Technical Writer. I’ve published a ton of technical content on the internet focused on web, mobile and system tech. And in this blog, I focus on sharing my views on Tech, Products, Teams, and Programming and the things I am working on. If you love my content and wish to stay in the loop, then by all means share this page and bookmark this website.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.