A commonly asked question in Node.js interview — What is Event loop?

Lizen Shakya
5 min readJun 26, 2021

Have you ever given an interview for a position as a Node.js developer?

The first question usually asked by an interviewer is :

Can you tell me about Node.js and why is it popular?

So, the obvious answer will be:

Node.js is a server-side JavaScript run-time environment. It’s open-source, including Google’s V8 engine, a Libuv for cross-platform compatibility, and a core library. Notably, Node.js does not expose a global “window” object, since it does not run within a browser.

Node.js is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It’s used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind.

Then the next question will usually be as

Node.js is a non-blocking, event-driven server, due to its single-threaded nature can you tell us more about the event loop?

Node.js is a single-threaded event-driven platform that is capable of running non-blocking, asynchronous programming. These functionalities of Node.js make it memory efficient. The event loop allows Node.js to perform non-blocking I/O operations despite the fact that JavaScript is single-threaded. It is done by assigning operations to the operating system whenever and wherever possible.

The event loop is the secret behind JavaScript’s asynchronous programming. JS executes all operations on a single thread, but using a few smart data structures, giving us the illusion of multi-threading.

The event loop is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.

Event Loop

Example:

console.log("This is the first thing to process");
setTimeout(function(){
console.log("This is the second thing to process");
}, 3000);
console.log("this is the third thing to process");

Output

This is the first thing to process
this is the third thing to process
This is the second thing to process

But in our mind, the output should be,

This is the first thing to process
This is the second thing to process
this is the third thing to process

which is wrong, let me explain this,

In the above example,

  1. The first console log statement is pushed to the call stack, and “This is the first thing to process” is logged on the console and the task is popped from the stack.
  2. Next, the setTimeout is pushed to the queue and the task is sent to the Operating system and the timer is set for the task.
  3. This task is then popped from the stack.
  4. Next, the third console log statement is pushed to the call stack, and “this is the third thing to process” is logged on the console and the task is popped from the stack.
  5. When the timer set by setTimeout function (in this case 3000 ms) runs out, the callback is sent to the event queue.
  6. The event loop on finding the call stack empty takes the task at the top of the event queue and sends it to the call stack.
  7. The callback function for setTimeout function runs the instruction and “This is the second thing to process” is logged on the console and the task is popped from the stack.

Note: In the above case, if the timeout was set to 0ms then also the statements will be displayed in the same order. This is because although the callback with be immediately sent to the event queue, the event loop won’t send it to the call stack unless the call stack is empty i.e. until the provided input script comes to an end.

As Node.js is a single threaded event driven platform, it will not wait for the heavy task to be completed. It will send those task to the event queue and execute the next task. And at last if the task is completed, it will get the callback result.

The event loop got its name because of how it’s usually implemented, which usually resembles:

while (queue.waitForMessage()) {
queue.processNextMessage()
}

Phases of Event Loop

phases of event loop

The Event Loop is composed of the following six phases, which are repeated for as long as the application still has code that needs to be executed:

  1. Timers: Callbacks scheduled by setTimeout() or setInterval() are executed in this phase.
  2. I/O Callbacks: Executes I/O callbacks deferred to the next loop iteration.
  3. Waiting / Preparation: Internally used only
  4. I/O Polling: This is the phase in which all the JavaScript code that we write is executed, starting at the beginning of the file, and working down.
  5. setImmediate() callbacks: It invokes setIntermediate() callbacks.
  6. Close events: This phase executes the callbacks of all close events.

The Event Loop starts at the moment Node.js begins to execute your application entry point.

These six phases create one cycle, or loop, which is known as a tick. A Node.js process exits when there is no more pending work in the Event Loop, or when process.exit() is called manually. A program only runs for as long as there are tasks queued in the Event Loop, or present on the call stack.

Summary:

  1. Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks.
  2. The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task.
  3. When task starts in nodejs it will not wait for the heavy task to be completed. It will send those task to the event queue and execute the next task.

Thank you…….

References:

--

--