Event Loop in 2 Minutes

September 20, 2024 (2mo ago)

Event Loop in 2 Minutes

What is the Event Loop?

The Event Loop is a mechanism in JavaScript that allows the runtime to handle asynchronous operations. It ensures that JavaScript remains responsive and non-blocking by managing the execution of multiple tasks in a single-threaded environment.

How Does the Event Loop Work?

  1. Single Threaded Execution: JavaScript is single-threaded, meaning it can only execute one task at a time. This is managed by Call Stack, where functions are executed in a synchronous manner (means one by one).

  2. Call Stack: The main thread in JavaScript where synchronous code is executed. It keeps track of the currently executing function.

Think of Call Stack as a stack of plates.
Every time a function is called,
a new plate (function) is added to the stack.
When a function completes,
its plate (function) is removed from the stack.
  1. Web APIs: For Async operations like setTimeout, HTTP Requests, fetch, and DOM Events, JavaScript uses Web APIs provided by the browser. These operations are handled outside the Call Stack.

  2. Callback Queue: When an async operation completes, the callback function is added to the Callback Queue. This Queue waits untill the call stack is clear to push the callback function to the call stack.

  3. Event Loop: The Event Loop continuously checks the Call Stack and Callback Queue. If the Call Stack is empty, it moves the first function from the Callback Queue to the Call Stack for execution.

  4. Microtask Queue: For Promises and Mutation Observer, JavaScript maintains a separate queue called Microtask Queue. Microtasks have higher priority than Callback Queue tasks. The Event Loop checks the Microtask Queue First, then the Callback Queue.

That's the Event Loop in a nutshell! It's a crucial part of JavaScript's runtime environment, ensuring that asynchronous operations are handled efficiently and that the application remains responsive.

Interviewer: Welcome to the Team!! 😎🚀