My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

What's the difference between process.nextTick() and setImmediate()?

slim's photo
slim
·Jun 3, 2019

I found this question mentioned above on this wbesite and in many different websites, and as an answer there is mentioned:

The difference between process.nextTick() and setImmediate() is that process.nextTick() defers the execution of an action till the next pass around the event loop or it simply calls the callback function once the ongoing execution of the event loop is finished whereas setImmediate() executes a callback on the next cycle of the event loop and it gives back to the event loop for executing any I/O operations.

I found the answer is a little bit sophisticated and is not clear, what I understand is the process.nextTick() has the highest priority to execute the code when it setImmediate() exists.

function nextTickCb() {
    console.log('Processed nextTickCb');
}

function immediateCb() {
    console.log('Processed immediateCb');
} 

setImmediate(immediateCb)
process.nextTick(nextTickCb);
console.log('Process in the first Iteration')

The code returns:

Process in the first Iteration
Processed nextTickCb
Processed immediateCb

According to Node.js official documentation, process.nextTick() will be executed after the current operation is completed, regardless of the current phase of the event loop.