DEV Community

Bhat Aasim
Bhat Aasim

Posted on

Event Loop in 2 Minutes

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.
Enter fullscreen mode Exit fullscreen mode
  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!! 😎🚀

Top comments (3)

Collapse
 
piyuuussshhh profile image
Piyush Udhao

Thank you for this!!

Collapse
 
bhataasim profile image
Bhat Aasim • Edited

You are Welcome, Now every day I will try to share the Amazing Stuff. Thanks ❣️

Collapse
 
efpage profile image
Eckehard

While Javascript does not know real multitheading, the Javascript engine does! The main program is executed in one thread, the event loop runs in another. So, in fact there can be two tasks running in parallel. Even if you block the main program with an endless loop, timers will still run and events will fire. But if you run an endless loop inside an event, all background task will stop (even events will not fire anymore).

See this post) for more details.