a blog for those who code

Friday 10 April 2015

Difference between process.nextTick() and setImmediate()

In this post we are going to discuss about the differences between process.nextTick() and setImmediate(). The main difference between the two is that process.nextTick() queues its callbacks before I/O callbacks whereas setImmediate() queues its callbacks after I/O callbacks.


In my previous post about Usage of process.next() we have learnt that process.nextTick() defer the execution of an action till the next pass around the event loop or simply it calls the callback function once the current execution of the event loop is finished.


On the other hand setImmediate() is been introduced with a purpose just opposite to that of process.nextTick(). setImmediate executes a callback on the next cycle of the event loop and gives back to the event loop for executing any I/O operations. According to NodeJS.org setTimeout() is there to schedule execution of a one-time callback after delay milliseconds. It returns a timeoutObject for possible use with clearTimeout().

Example :

function a() {
    setImmediate(function() {
   console.log('setImmediate');
    });
    for(var i = 0; i < 5; i++)
    {
    console.log('Inside Function ' + i);
    process.nextTick(function() 
    {
    console.log('Something ' + i)
    });
    }
}
a();

Output :

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment