JavaScript Course
JavaScript
/
Advanced

Microtasks vs Macrotasks

Definition

JavaScript divides asynchronous tasks into two distinct queues. The Macrotask Queue (setTimeout, setInterval, I/O) and the Microtask Queue (Promises, MutationObserver). The Microtask queue always has strictly higher priority.

Explain Like I'm New

Imagine the JS engine is a doctor. Macrotasks are scheduled patient appointments. Microtasks are emergency room patients. When the doctor finishes their current appointment, they check the ER (Microtask queue). They will process EVERY ER patient until the room is empty before they accept the next scheduled appointment (Macrotask).

Real World Example

If you call a `setTimeout(cb, 0)` and a `Promise.resolve().then(cb)` at the exact same time, the Promise callback will ALWAYS execute first because it enters the VIP Microtask queue.

Common Use Cases

  • •Predicting exact code execution order
  • •Preventing UI blocking

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Which queue has higher priority: Microtasks or Macrotasks?

intermediate

  • Give examples of Microtasks and Macrotasks.

advanced

  • What happens if a Microtask schedules another Microtask recursively?

Flash Cards

Question

Examples?

Click to reveal answer
Answer

Microtasks: `Promise.then/catch/finally`, `MutationObserver`, `queueMicrotask()`. Macrotasks: `setTimeout`, `setInterval`, `setImmediate` (Node), I/O callbacks, UI rendering events.

Question

What happens if a Microtask schedules another Microtask recursively?

Click to reveal answer
Answer

The Event Loop will be blocked! Because the Event Loop refuses to move on to the next Macrotask (or UI Render) until the Microtask queue is completely empty, an infinite loop of microtasks will freeze the browser.