Open In App
Related Articles

What is an event loop in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In JavaScript, the event loop is a fundamental mechanism that enables the asynchronous execution of code. It’s an essential part of the JavaScript runtime environment, allowing the language to handle non-blocking operations efficiently. The event loop is responsible for managing the execution of code, handling events, and maintaining the flow of control.

What does it mean when we say JavaScript is single-threaded?

It means that the main thread where JavaScript code is run, runs in one line at a time manner and there is no possibility of running code in parallel.

How do Event loops work?

  1. Call Stack:
    • JavaScript uses a call stack to keep track of the currently executing function (where the program is in its execution).
  2. Callback Queue:
    • Asynchronous operations, such as I/O operations or timers, are handled by the browser or Node.js runtime. When these operations are complete, corresponding functions (callbacks) are placed in the callback queue.
  3. Event Loop:
    • The event loop continuously checks the call stack and the callback queue. If the call stack is empty, it takes the first function from the callback queue and pushes it onto the call stack for execution.
  4. Execution:
    • The function on top of the call stack is executed. If this function contains asynchronous code, it might initiate further asynchronous operations.
  5. Callback Execution:
    • When an asynchronous operation is complete, its callback is placed in the callback queue.
  6. Repeat:
    • The event loop continues this process, ensuring that the call stack is always empty before taking the next function from the callback queue.

Example: In this example, a JavaScript script demonstrates synchronous blocking behavior. It starts by logging “Before delay,” then uses a function delayBySeconds to create a delay of 5 seconds using a busy-wait loop. The script then logs “After delay” after the 5-second delay completes.

Javascript

console.log("Before delay");
 
function delayBySeconds(sec) {
   let start = now = Date.now()
   while(now-start < (sec*1000)) {
     now = Date.now();
   }
}
 
delayBySeconds(5);
 
// Executes after delay of 5 seconds
console.log("After delay");

                    

Output:

Before delay
(... waits for 5 seconds)
After delay

Memory allocation in JavaScript

Heap memory

Data stored randomly and memory allocated.

Stack memory

Memory allocated in the form of stacks. Mainly used for functions.

Function call stack

The function stack is a function that keeps track of all other functions executed in run time. Ever seen a stack trace being printed when you ran into an error in JavaScript? That is nothing but a snapshot of the function stack at that point when the error occurred.

Example: This example shows how fuction goes into stack whenever a function is called.

Javascript

function LevelTwo() {
   console.log("Inside Level Two!")
}
 
function LevelOne() {
   LevelTwo()
}
 
function main() {
   LevelOne()
}
 
main()

                    

Order at which functions get executed i.e get popped out of the stack after a function’s purpose gets over as shown below:

Event loop

An event loop is something that pulls stuff out of the queue and places it onto the function execution stack whenever the function stack becomes empty.

The event loop is the secret by which JavaScript gives us an illusion of being multithreaded even though it is single-threaded. The below illusion demonstrates the functioning of the event loop well:

Here the callback function in the event queue has not yet run and is waiting for its time into the stack when the SetTimeOut() is being executed and the Web API is making the mentioned wait. When the function stack becomes empty, the function gets loaded onto the stack as shown below:

That is where the event loop comes into the picture, it takes the first event from the Event Queue and places it onto the stack i.e. in this case the callback function. From here, this function executes calling other functions inside it, if any.

This cycle is called the event loop and this is how JavaScript manages its events.



Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads