How process.nextTick() works in Node.js?

The process object is a one of the few global objects provided by the Node.js core API. It can be access from anywhere, thus its methods can also be accessed. Such is a method called process.nextTick() which is used by developers in realtime applications everyday to defer the execution of a function until the next Event Loop Iteration.

Browser JavaScript introduced us functions like setTimeout() to defer tasks. The setTimeout() function takes a callback function and a number value representing the time after which the callback function will be executed, in milliseconds.

setTimeout(callback, 0)

In Node.js, each iteration of an Event Loop is called a tick. To schedule a callback function to be invoked in the next iteration of the Event Loop, we use process.nextTick(). It just takes a callback with no time bound, since it will be executing in the next iteration of the Event Loop.

process.nextTick(callback)

The difference between setTimeout() and process.nextTick() is that the process.nextTick() function is specific to the Node.js Event Loop. setTimeout() uses JavaScript runtime to schedule its own queue of events. When using process.nextTick(), callback function associated with it runs immediately after events in the Event Queue are processed by the Event Loop in a single iteration. In comparison to setTimeout(), it is faster since queue associated with setTimeout() or the JavaScript runtime.

function cb(){
  console.log('Processed in next iteration');
}
process.nextTick(cb);
console.log('Processed in the first iteration');

The above snippet is an example of how process.nextTick() works. You can save the snippet in a file.js and run using $node file.js from your terminal. You will definitely notice that the second console.log printed before the console.log associated with function cb().

Processed in the first iteration
Processed in next iteration
Sample Test : nextTick.js 

for (var i = 0; i < 1024 * 1024; i++) {
  process.nextTick(function () { Math.sqrt(i) } )
}

Output : time node nextTick.js 

real	0m1.030s
user	0m1.014s
sys	0m0.113s
 setTimeout.js 

for (var i = 0; i < 1024 * 1024; i++) {
  setTimeout(function () { Math.sqrt(i) }, 0)
}

output : time node setTimeout.js 

real	0m1.236s
user	0m1.227s
sys	0m0.089s

More Info: Medium

About

My Name is Dileep Singh, Noder, Javascript Lover & NoSql Developer, Fitness Freak, Love to travel new places, learning photography & Music Manic ♯ ♩ ♬

Posted in Node.Js

Leave a Reply

Your email address will not be published. Required fields are marked *

*