Loading Now

Event Loop in JavaScript: Detailed explanation and practical example

Event Loop in JavaScript

JavaScript is a single-threaded programming language. This means it can only perform one operation at a time. However, JavaScript effectively handles multiple asynchronous tasks such as fetching data from servers or responding to user events through a mechanism known as the Event Loop.

How the Event Loop Works

How-the-Event-Loop-Works-1024x585 Event Loop in JavaScript: Detailed explanation and practical example

Call Stack

When JavaScript executes, it uses a Call Stack to manage function calls sequentially. These functions execute immediately and in order.

Callback Queue and Microtask Queue

Asynchronous tasks like setTimeout, API requests, or user interactions (clicking, scrolling, etc.) don’t execute immediately. Instead, they are placed into separate queues known as the Callback Queue or Microtask Queue.

Event Loop

The Event Loop continuously monitors the Call Stack. Once the Call Stack is empty, the Event Loop will first execute tasks from the Microtask Queue, followed by those in the Callback Queue.

Example Illustration

Here’s a practical example to clearly illustrate how the Event Loop operates:

console.log("Program execution starts");

// setTimeout is a common JavaScript timer function
setTimeout(() => {
  console.log("Executed after setTimeout with 0-second delay");
}, 0);

// Promise.resolve is a key method for handling Promises
Promise.resolve().then(() => {
  console.log("Promise executed as soon as possible");
});

console.log("Program execution ends");

Output

Program execution starts
Program execution ends
Promise executed as soon as possible
Executed after setTimeout with 0-second delay

Why this Output?

This output occurs because the Promise is placed in the Microtask Queue, which has higher priority than the Callback Queue. Hence, it executes before the setTimeout callback, even though the timer delay is set to 0 seconds.

Conclusion

Thanks to the Event Loop, JavaScript smoothly handles asynchronous tasks. This ensures the user interface remains responsive, providing a smoother and better user experience.

Read more:

REST API vs Stream API: Key Differences & Best Use Cases

What is an Associative Array? Simple Guide & Examples

Share this content:

Post Comment

Bạn có thể đã bỏ qua