Find your content:

Search form

You are here

Explain SetImmediate vs Process.nextTick

 
Share

SetImmediate

Event loop executes the setImmediate methods in a special way. Following diagram illustrate how event loop executes associated callbacks. setImmediate methods are part of the "Run Check Handles" callbacks. When event loop executes after the "Poll for I/O", it executes setImmediate callbacks under Run chek handles.

 

 

 

 

 

Process.nextTick

It schedules a function to be executed when the current tick ends.

In order to dig deeper, we first need to be familiar with one of the node's  Central c++ function.

MakeCallback which takes as parameter a Javascript function along with its arguments and its calling Object.

Essentially, its process boils down to two things

1. Execute the Javascript function
2. End the tick

The reason we say it's central to node is that every Javascript callback gets executed using MakeCallback when ever it comes off the event loop.

For example, when a TCP server receives a new connection, the connectionListener gets executed using MakeCallback.

Therefore a tick comprises all the code that runs in response to an event fired from the event loop.

 

console.log('Program started.');

setImmediate(function() {
  console.log('in immediate.');
  // another tick ends here
});

process.nextTick(function() {
  console.log('in nextTick.');
  // no tick ends here - another process.nextTick
  // would just append to the current tick's queue
});

console.log('end of first tick.');
// first tick ends here

Output:
Program started.
end of first tick.
in nextTick.
in immediate.



Since process.nextTick callbacks execute before going back to the event loop, they run before setImmediate callbacks.
And when setImmediate callbacks get fired from the event loop using MakeCallbackthey end a tick!

 

 

My Block Status

My Block Content