Asynchronous code and events

Understanding process.nextTick()

Understand how Node.js process.nextTick() works with the event loop, running your callback at the end of the current operation before the next tick starts.

As you try to understand the Node.js event loop, one important piece is process.nextTick().

Every time the event loop completes a full trip, we call it a tick.

When you pass a function to process.nextTick(), you tell the engine to run it at the end of the current operation, before the next event loop tick starts:

process.nextTick(() => {
  //do something
})

The event loop is busy running the current function. When that operation ends, Node runs every function you queued with nextTick during that operation.

This is how you ask Node to run something asynchronously (after the current function), but as soon as possible. It does not go into the timer queue.

Compare that with setTimeout(() => {}, 0). That runs at the end of the next tick, much later than nextTick(), which gets priority and runs just before the next tick begins.

Here is a small demo you can paste into a file called tick-demo.js:

console.log('start')

process.nextTick(() => console.log('next tick'))

setTimeout(() => console.log('timeout'), 0)

console.log('end')

Run node tick-demo.js and you should see:

start
end
next tick
timeout

start and end print first because they are synchronous. next tick runs before timeout because process.nextTick() always wins over a zero-delay timer.

Use nextTick() when you need code to run before the event loop moves on to the next phase. A common case is finishing setup in a constructor before a 'ready' event fires.

Be careful with recursion. If every nextTick callback schedules another nextTick, you can starve timers and I/O. Use it for short ordering fixes, not for breaking up heavy work.

Try this on your own machine: run the demo above and confirm the order on your Node version.

Lesson completed