🔄 Event Loop
jsadvanced

🔄Event Loop

The Event Loop enables non-blocking behavior in JavaScript by coordinating the call stack, microtask queue, and macrotask queue.

Memory Trick

Think: Sync → Microtask (drain all) → Render → Macrotask (one). Promises before timers, always.

Log in to track your mastery & progress

1️⃣ Definition (WHAT)

The Event Loop is the mechanism that allows JavaScript to perform non-blocking asynchronous operations by coordinating the call stack, Web APIs, microtask queue, and macrotask queue.

In short: it decides what runs next in JavaScript.

2️⃣ Architecture

ComponentRole
Call StackExecutes synchronous code, one at a time
Web APIsHandle async operations (setTimeout, fetch, DOM events)
Microtask QueuePromise .then/.catch/await callbacks
Macrotask QueuesetTimeout, setInterval, DOM events
Event LoopOrchestrates all of the above

3️⃣ Execution Order (HOW)

  1. Run all synchronous code (drain call stack)
  2. Drain entire microtask queue (all Promises, queueMicrotask)
  3. Browser can repaint (if needed)
  4. Take one macrotask (setTimeout, etc.)
  5. Repeat

Microtasks always have higher priority than macrotasks.

js
console.log("start"); setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); console.log("end"); // Output: start → end → promise → timeout

4️⃣ Microtask vs Macrotask

Microtasks (higher priority):

  • Promise.then, Promise.catch, async/await
  • queueMicrotask()
  • MutationObserver
  • Queue is fully drained before any macrotask runs

Macrotasks (lower priority):

  • setTimeout, setInterval
  • DOM events (click, scroll)
  • setImmediate (Node.js)
  • Only one macrotask per event loop cycle

5️⃣ Can Microtasks Block Rendering?

Yes. Rendering happens only after:

  1. Call stack is empty
  2. Microtask queue is empty

If microtasks keep scheduling new microtasks → UI freezes.

js
function infiniteMicrotask() { Promise.resolve().then(infiniteMicrotask); } infiniteMicrotask(); // Browser hangs — never reaches render!

6️⃣ How await affects execution

await pauses the async function and returns control to the caller. Code after await is scheduled as a microtask.

js
async function foo() { console.log('A'); await Promise.resolve(); console.log('B'); // microtask } console.log('1'); foo(); console.log('2'); // Output: 1 → A → 2 → B

Was this helpful?

Test your Knowledge

4 questions to cement what you just learned.