Open In App

Explain the Mechanism of event loop in Node.js

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript is a single-threaded, non-blocking, asynchronous language that uses the concept of event loop to make it work asynchronously even if it is single-threaded.

Feature: The Event Loop is responsible for sending functions from the event queue to the Stack for processing when it becomes empty. 

Mechanism of Event Loop: There are some functions in javascript which can run on the browser API instead of on V8. The functions or call which is not present on V8 are sent to the browser API and then work as a single thread as executed itself. After its execution, the resulting output is sent to the Event Queue. The Event Loop is responsible for sending functions’ results to the Stack for processing when it becomes empty.

Example: Let’s understand it by using a simple example.

Javascript




console.log("Hello");
  
setTimeout(console.log("Hello-2"), 3000);
  
function sum(a, b) {
    console.log(a + b);
}
  
sum(2, 4);


Output:

Hello
6
Hello-2

Explanation: The execution flow starts from

console.log("Hello");

and at the time it reaches the setTimeout function

setTimeout(console.log("Hello-2"), 3000);

It sends the function to the browser API where the function starts to execute, while in the meantime the next operation in the Stack is executed which is 

sum(2, 4) ;

Then when the setTimeout function completed its execution it sends it to the Event Queue and waits for the completion of the running operations in the Stack, when the Stack finishes its operation, the Event Loop sends the setTimeout function from the Queue to the Stack, and Stack finally processed it.

--Stack--

sum(2, 4)
setTimeout(console.log("Hello-2"), 3000)
console.log("Hello")

Last Updated : 26 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads