Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
Why is the Event Loop Important?
The event loop is a critical component of JavaScript's runtime, particularly in Node.js, enabling non-blocking, asynchronous programming. It ensures that operations like I/O, timers, and callbacks execute efficiently without blocking the main thread, making JavaScript highly suitable for handling concurrent tasks. The event loop processes tasks in phases, allowing the system to handle numerous operations simultaneously with minimal overhead, ensuring smooth and responsive applications.
Features of Node.js Event Loop
Asynchronous and Non-Blocking: Handles I/O operations without blocking the main thread, enabling efficient multitasking.
Phases of Execution: Operates in phases (e.g., timers, pending callbacks, idle/prepare, poll, check, and close callbacks) to manage tasks systematically.
Timer Management: Executes callbacks scheduled by setTimeout and setInterval in the timers phase.
Callback Queue: Processes asynchronous callbacks, including those from I/O operations and promises.
Continuous Execution: Keeps running as long as there are pending tasks, making it the heart of Node.js's runtime.
Efficient Resource Utilization: Maximizes performance by utilizing a single-threaded model for most tasks while delegating heavy operations to worker threads.
Integration with Promises: Supports microtask queues for promises, ensuring their callbacks are executed before moving to the next phase.
Event-Driven Architecture: Facilitates building scalable and responsive applications using an event-based approach.
Working on 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 of Event Loop in Node.js
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.
We invoke the function bar. It returns a setTimeout function.
The callback we passed to setTimeout gets added to the Web API, the setTimeout function and bar get popped off the call stack.
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.
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.
The callback logs Second.
Let's see the visual representation of the above steps below.
The step-by-step process is given below:
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.
Yes, Node.js uses a single-threaded event loop for JavaScript execution, delegating heavy tasks like I/O to worker threads or the system kernel.
Why Node.js is event-driven?
Node.js is event-driven to handle asynchronous operations efficiently, enabling non-blocking execution and high scalability, ideal for real-time or I/O-intensive applications.
What is the life cycle of the event loop?
The event loop cycles through phases (Timers, Callbacks, Poll, Check, Close, etc.), processing queued tasks until no more remain, ensuring continuous operation.
Conclusion
The event loop is the cornerstone of Node.js, enabling its non-blocking, asynchronous architecture and making it highly efficient for handling concurrent operations. By managing tasks across multiple phases, the event loop ensures smooth execution of I/O operations, timers, and callbacks without blocking the main thread. Its event-driven design allows developers to build scalable, real-time, and responsive applications with ease.
You can useCode360to practise questions on web development and use the Code360 Self-paced Web developmentto grasp numerous web development concepts.