DEV Community

Prathamesh Lakare
Prathamesh Lakare

Posted on

Understanding the JavaScript Event Loop

If you've ever wondered how JavaScript handles asynchronous tasks like setTimeout, fetch, or Promises while being a single-threaded language—you're not alone.


How JavaScript Executes Code

JavaScript runs in the browser using a JavaScript engine. When your code executes, it goes into the call stack, which handles synchronous tasks—code that runs line by line.

But when there's asynchronous code, things work a bit differently.


Web APIs

The browser provides Web APIs to handle asynchronous operations.

When such code runs, it's sent off to the Web API environment provided by the browser—not the call stack. Once the asynchronous operation is complete, its callback is moved to the callback queue (or task queue).


Microtasks vs Macrotasks

Not all tasks in the callback queue are treated equally.

  • Microtasks: Promises, queueMicrotask, MutationObserver
  • Macrotasks: setTimeout, setInterval, setImmediate, UI rendering

Microtasks have higher priority and are always executed before macrotasks in each cycle of the event loop.


Event Loop

The event loop is the behind-the-scenes mechanism that keeps everything running smoothly.

It constantly checks: Is the call stack empty?

If yes, it picks the first task from the callback queue (starting with microtasks) and moves it into the call stack for execution.

This is how JavaScript handles asynchronous code without blocking the main thread.

Top comments (0)