Event Loop in Node.js ๐Ÿš€

Event Loop in Node.js ๐Ÿš€

ยท

5 min read

Hey there..! ๐Ÿ‘‹

In the early days of the internet, websites often consisted of static data on an HTML page. But today, web applications have evolved into more interactive and dynamic, it has become increasingly necessary to do intensive operations like making external network requests to retrieve API data. To handle these operations in JavaScript, a developer must use asynchronous programming techniques.

Let's dive into the topic directly.

Node.js is a single-threaded asynchronous event-driven JavaScript runtime that is designed to build scalable network applications. These functionalities make Node.js memory efficient. Since JavaScript can only execute one statement at a time, it needs the event loop to be informed of when to execute which specific statement. The event loop handles this with the concepts of a stack and a queue. We'll discuss stack, queue, and other core components later.

Here we go! let's discuss the Event loop. ๐Ÿ”

What is an event loop? ๐Ÿค”

Event Loop.jpg

The term event loop is self-explanatory and the secret behind the Asynchronous nature of JavaScript. It is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.

The event loop allows Node.js to perform non-blocking I/O operations even though single-threaded. This is achieved by assigning the blocking I/O operations to the operating system whenever possible.

Whenever we execute the JS code, a thread is automatically created. Since most modern OS are multi-threaded, they can handle multiple operations executing in the background. When one of these operations is completed, it is pushed to the callback queue. Once all the non-blocking operations are completed, the stack is empty. Then, the runtime starts handling the callback queue to be processed by pushing it into the stack. Each operation has an associated callback function that gets called to handle the operation.

The processing of functions continues until the stack is once again empty. Then, the event loop will process the next operations in the callback queue (if there is one).

Feature of the Event Loop ๐Ÿค“

  • An event loop is an endless loop, which waits for tasks, executes them, and then sleeps until it receives more tasks.

  • It executes tasks from the event queue only when the call stack is empty i.e., there is no ongoing task.

  • It allows us to use callback and promise.

  • It executes the tasks starting from the oldest first.

Example 1:

function first() {
  console.log("This is the first statement");
}

function second() {
  console.log("This is second statement");
}

function third() {
  console.log("This is the third statement");
}

first();
second();
third();

Output:

This is the first statement
This is the second statement
This is the third statement

Explanation: Since we don't have any block operations, it prints in the execution order.

Example 2:

console.log("This is the first statement");

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

console.log("This is the third statement");

Output:

This is the first statement
This is the third statement
This is the second statement

Explanation:

  1. In the above example, the first console log statement is pushed to the call stack as the task, the console is logged, and the task is popped from the stack.

  2. Next, the setTimeout is pushed to the queue and the task is sent to the OS, and the timer is scheduled for the task and then popped from the stack.

  3. Next, the last console log statement is pushed to the call stack as the task, the console is logged and then popped from the stack.

  4. When the timer set by the setTimeout function runs out, the callback is sent to the event queue. 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. The callback function for the setTimeout function runs the instruction and "This is the second statement" is logged on the console and the task is popped from the stack.

Note: Consider the above example, If the timeout is set to 0ms, then also the statement will be displayed in the same order. This is because the callback is 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 task comes to an end.

Zero delays

Zero delays don't mean the callback will fire off after zero milliseconds. Calling the setTimeout is set to 0ms, then also the statement will be displayed in the same order. This is because the callback is 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 task comes to an end.

Example:

console.log("This is the first statement");

setTimeout(function() {
      console.log("This is second statement");
}, 0);  // <== Note: setTimeout is 0

console.log("This is the third statement");

Output:

This is the first statement
This is the third statement
This is the second statement

When should I utilize the event loop? ๐Ÿ˜€

  • When you need to do the heavy computation, which is not required to run synchronously, means the next statement can be executed without depending on the previous statement. In that case, you would not want to block the main thread because of the computation.

  • When you want to execute your code in the end, after all the other statements/functions are done executing.

That's it, guys. I hope you liked this article and please feel free to drop your thoughts about this article.

Thanks for reading and see you. ๐Ÿ‘‹๐Ÿ˜‰

Reference

ย