Event Loop in Node.js

SHUBHAM AGARWAL
Last Updated: May 13, 2022

Introduction

Node.js is a JavaScript runtime based on Chrome's V8 JavaScript motor, which utilises an occasion driven, non-obstructing I/O model, making it lightweight and effective.

 

One of the most crucial components of Node.js to understand is the Event Loop. It shows how Node.js can be asynchronous and have non-blocking I/O. It essentially explains the "killer app" of Node.js, the thing that has made it so popular.

 

The JavaScript code in Node.js runs in a single thread. At any one time, just one thing is happening. This limitation is rather beneficial, as it makes programming a lot easier without worrying about concurrency difficulties.

 

In this article, we’ll decode the event loop in Node.js.

Node js Event Loop

The event loop of Node js allows node.js to perform non-blocking input-output operations even though JavaScript is single-threaded. 

 

The Node.js JavaScript is single-threaded, which means it can only run one process at a time. Usually, this isn't a significant concern, but imagine you're performing a task that takes 30 seconds. We have to wait 30 seconds for anything else to happen during that process (JavaScript runs on the browser's main thread by default, so the entire UI is stuck). Nobody wants a slow, unresponsive website in 2021.

Fortunately, the browser provides us with a Web API, which the JavaScript engine does not. This includes things like the DOM API, setTimeout, and HTTP requests, among other things. This can assist us in implementing some async, non-blocking behaviour.

Working of Event Loop

The image below shows the working of the event loop in node.js.

 

The setTimeout function is returned by the response function. 

 

  • The Web API provides us with the setTimeout method, which allows us to delay actions without interrupting the main thread. 
  • The arrow function () => return 'Hey', the callback function we gave to the setTimeout function, is added to the Web API. 

 

Meanwhile, the setTimeout and reply functions have been popped off the stack, and they have both returned their values!

 

A timer in the Web API runs for the duration of the second argument, 1000ms. The callback is passed to something called the queue rather than being immediately added to the call stack.

 

This can be misunderstood: it does not imply that the callback function is added to the call stack(and thus produces a value) after 1000ms! After 1000ms, it is just added to the queue. But, because it's a queue, the function must wait its turn!

 

This is the part we've all been looking forward to, and it's time for the event loop to get down to business and link the queue to the call stack! The first item in the queue is added to the call stack if it is empty if all previously executed functions have returned their values and have been pulled off the stack. Because no other functions were called in this situation, the call stack was empty when the callback function was placed first in the queue.

 

 

The callback is added to the call stack, gets invoked, returns a value, and gets popped off the stack.

Example to Explain Event Loop

Let's write a basic code to understand what is logged to the terminal when we run the code below and take a quick look at what happens when we run this code in the browser.

const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");
bar();
foo();
baz();

 

  1. We invoke the function bar. It returns a setTimeout function.
  2. The callback we passed to setTimeout gets added to the Web API, the setTimeout function and bar get popped off the call stack.
  3. The timer runs. In the meantime, foo gets invoked and logs First. foo returns (undefined), baz gets invoked, and the callback gets added to the queue.
  4. baz logs Third. The event loop sees the call stack is empty after baz returns, after which the callback gets added to the call stack.
  5. The callback logs Second.

 

Let's see the visual representation of the above steps below.

Step by Step process to see what’s 

Asynchronous Functions

We know JavaScript is asynchronous, and so is Node. The main principle behind Node is that an application gets executed on a single thread or process, and thus the events are handled asynchronously.

 

Let us consider any typical web server like Apache. If we look carefully, it requires separate threads for every process until the request is satisfied. The main disadvantage of multi-thread is that they are not memory intensive and don't scale very well. Also, we need to ensure that each process must be thread-safe, and deadlock should not appear in the process.

 

But Node does things differently. Once we start a Node application, it creates a single thread of execution. As the Node receives a request, it assigns the request to the thread to that process, and no other requests are processed until it has finished processing the code for the present request. Therefore, Node can handle multiple requests simultaneously with the help of event loop and callback functions.

 

In Node applications, once the Node initiates the request, it does not wait around for the request to get the response. Instead of that, it attaches a callback for the request. When the request has been completed, or once the response has been received by request, the callback function emits an event that does something with either the results of the requested action or with the resource requested.

 

If multiple people are accessing a Node application simultaneously, and the application needs to access a resource from a file, then the Node attaches a callback function with each request. As soon as the resource is available to that request, a callback function is called to every person's request. The Node can then handle other requests in the meantime.

 

Gif Credits: https://dev.to/lydiahallie/

Frequently Asked Questions

1). What is the event loop in Node js?

Answer: The event loop allows Node.js to perform non-blocking input /output operations even though JavaScript is single-threaded by offloading operations to the system kernel whenever possible.

 

2). What is Node js?

Answer: Node.js is a JavaScript runtime based on Chrome's V8 JavaScript motor, which utilises an occasion driven, non-obstructing I/O model, making it lightweight and effective.

 

3). What are asynchronous functions?

Answer: An asynchronous function is initialised with the async keyword, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behaviour to be written in a better style, avoiding the need to configure promise chains explicitly.

Key takeaways

In this blog, we decoded the event loop in node.js. We also saw how it works with the help of visuals.

 

You can use CodeStudio to practise questions on web development and use the Coding Ninja Self-paced Web development to grasp numerous web development concepts.

 

Happy Learning!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think