Published Oct 04, 2019
[
 
]
Due to the fact that JavaScript is single-threaded i.e. it performs only a single process at a time, so it is the Event Loop that allows Node.js to perform non-blocking I/O operations.
At the start of a JavaScript program, an event loop is initialized. There are several operations that execute in an event loop. Below is the sequence in which different they are executed in a single iteration of the event loop. These operations are processed in a queue.
Whenever a new queue of operations is initialized we can think of it as a new tick. The process.nextTick() method adds the callback function to the start of the next event queue. It is to be noted that, at the start of the program process.nextTick() method is called for the first time before the event loop is processed.
When in Node.js, one iteration of the event loop is completed. This is known as a tick. process.nextTick() taking a callback function which is executed after completing the current iteration/tick of the event loop.
process.nextTick() schedule a callback function to be execute in next iteration of event loop.
Whenever we call setImmediate() method, it’s callback function is placed in the check phase of the next event queue. There is slight detail to be noted here that setImmediate() method is called in the poll phase and it’s callback functions are invoked in the check phase.
setImmediate(function A() {
console.log("1st immediate");
});
setImmediate(function B() {
console.log("2nd immediate");
});
process.nextTick(function C() {
console.log("1st process");
});
process.nextTick(function D() {
console.log("2nd process");
});
// First event queue ends here
console.log("program started");
program started
1st process
2nd process
1st immediate
2nd immediate
For the above program, event queues are initialized in the following manner:
D A B
Now functions D, A, B are executed in the order they are present in the queue.