Node.js Eventloop

Node.js is an event driven platform which is asynchronous. The event loop helps Node.js to carry out non-blocking I/O operations beyond JavaScript's limitation as a single threaded language. Most OS are multi threaded which allows you to perform more operations in the background. When one operation is completed the kernel tells Node.js and the corresponding callback set to the operation is added to the event queue. This will be executed later. Event loop waits for tasks and executes them and sleeps until another task is assigned. It lets us use the callbacks and promises. It follows a first in first out order in executing the tasks. 

Here is an example of eventloop.

console.log("This is the first statement"); 
   
setTimeout(function(){ 
    console.log("This is the second statement"); 
}, 1000); 
   
console.log("This is the third statement");

Output of the example:


This is the first statement

This is the third statement

This is the second statement


Phases of Eventloop

Timers- In this phase callbacks scheduled by setTimeout() and setInterval() are executed.

Pending callbacks-Executed I/O callbacks put off to the next loop iteration.

Idle,prepare - used internally.

Poll- fetches new I/O events and executes I/O related callbacks 

Check- setImmediate() callbacks are invoked.

Close callbacks- some close callbacks like socket.on(‘close’, ...)


When Node.js starts, the event loop is initialized and processes a given input script which may make async API calls, schedule timers and then starts processing the event loop. The console.log statements and setTimeout() functions will schedule a timer. To perform some asynchronous operations a special library module called libuv is used. There is a libuv thread pool in the node js logic to manage this thread pool libuv library is used.  To represent operations that are heavy for event loops, the thread pool has four threads. I/O operations, Opening and closing connections, setTimeouts are such heavy operations. When these operations are completed a callback function is called and it handles any error if present. The callback function is sent to the event queue and when the call stack is empty, the event passes through the event queue and sends a callback to the call stack.