Skip to content
SunnyWriteUps
Go back

Demystifying the JavaScript Event Loop, Microtasks, and Timers

Edit page

JavaScript Event Loop

Here is a breakdown of how JavaScript handles asynchronous operations under the hood.


The Core Actors

The Event Loop is a continuous process that moves callbacks between four main areas:

  1. The Call Stack: Where your synchronous JavaScript code executes. Functions are pushed onto the stack when called and popped off when they return.
  2. Web APIs / Node APIs: Features provided by the browser (like the DOM or fetch) or Node.js (like fs or crypto) that run tasks in the background.
  3. The Microtask Queue: A high-priority queue for critical, immediate follow-up work.
  4. The Macrotask Queue (Task Queue): A lower-priority queue for deferred work like timers and UI events.

Microtasks vs. Macrotasks

The most common source of asynchronous bugs is misunderstanding the priority difference between these two queues.

Whenever the Call Stack empties, the Event Loop follows a strict rule: Drain the Microtask Queue completely before touching the Macrotask Queue.

The Reality of Timers

A common misconception is that setTimeout(callback, 1000) guarantees the callback will run exactly 1,000 milliseconds from now.

In reality, timers dictate the minimum delay. After 1,000ms, the Web API pushes your callback into the Macrotask Queue. However, if the Call Stack is busy, or if the Microtask Queue is flooded with Promises, your timer callback has to wait in line. This is why setTimeout(..., 0) doesn’t execute instantly—it simply queues the task to run at the next available opportunity.

Modern Async Patterns

Today, async and await are the standard patterns for handling asynchronous code, providing a cleaner alternative to nested Promise chains (the infamous “callback hell”).

Under the hood, async/await is syntactic sugar over Promises. When the engine encounters an await keyword, it suspends the execution of that specific function and yields control back to the main thread. The remainder of the function is then scheduled as a Microtask to be executed once the awaited Promise resolves.

Practical Example: The Event Loop in Action

To solidify how the call stack, microtasks, and macrotasks interact, trace what gets printed in this classic code snippet:

console.log("1. Synchronous script start");

setTimeout(() => {
  console.log("2. setTimeout macrotask callback");
}, 0);

Promise.resolve().then(() => {
  console.log("3. Promise microtask callback 1");
}).then(() => {
  console.log("4. Promise microtask callback 2");
});

queueMicrotask(() => {
  console.log("5. queueMicrotask execution");
});

console.log("6. Synchronous script end");

Execution Output:

1. Synchronous script start
6. Synchronous script end
3. Promise microtask callback 1
5. queueMicrotask execution
4. Promise microtask callback 2
2. setTimeout macrotask callback

Step-by-Step Breakdown:

  1. Synchronous code runs first: console.log("1...") and console.log("6...") execute immediately in the Call Stack.
  2. Macrotask enqueued: setTimeout(..., 0) registers its callback into the Macrotask Queue (Task Queue).
  3. Microtasks enqueued: Promise.then and queueMicrotask register their callbacks into the Microtask Queue.
  4. Microtask Queue Drained: Before the Event Loop considers picking up the setTimeout callback, it completely empties the Microtask Queue in FIFO order, resolving chained promises as they settle.
  5. Macrotask Picked Up: Only after all microtasks have finished does the Event Loop move to the next macrotask: executing the setTimeout callback.

Key Takeaways for Frontend Developers


Edit page
Share this post on:

Previous Post
Getting Started Building Reactive 3D Scenes for Production
Next Post
Building Browser-Based Media Tools The Power of Canvas and WebAssembly

Comments