Skip to the page

The event loop · core

Microtasks vs macrotasks in practice

A macrotask (task) is one unit of work such as a timer callback or a click handler, and one runs per loop turn; microtasks (promise reactions, await continuations, queueMicrotask, MutationObserver) all run right after the current task, before rendering or the next task.

The notes

What you must know

  • A then callback is queued as a microtask only when its promise settles. A pending promise queues nothing.
  • new Promise(r => setTimeout(r, 5000)) is a timer task wrapped in a promise. 'A promise and a setTimeout both with 5 seconds' is a trick question: the timer inside decides.
  • Microtasks queued inside a timer callback run before the next timer callback (Node 11+ behaves like browsers here).
  • Each .then in a chain is queued only after the previous step finishes, so two chains interleave one step at a time.
  • Use microtasks to finish work right after the current operation (frameworks batch updates this way). Use tasks (setTimeout, MessageChannel, scheduler.postTask) to yield so the browser can render and handle input.
  • MutationObserver callbacks are microtasks. requestAnimationFrame callbacks are part of the rendering steps, not a task queue.

The red pen

Common traps: mistake → fix

  • Mistake: Microtasks are faster

    Fix: they run sooner, not faster; too many of them block rendering.

  • Mistake: Two .then chains run one after the other

    Fix: they interleave step by step.

  • Mistake: setTimeout(0) vs setImmediate has a fixed order

    Fix: in Node's main module it is not deterministic.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between microtasks and macrotasks? Give examples other than Promise and setTimeout.
  2. A Promise and a setTimeout both have a 5-second delay. Which runs first? (Flipkart 2025)
  3. Predict two interleaved then-chains.
  4. Why do frameworks batch updates in a microtask?
  5. When would you deliberately use a task (MessageChannel or postTask) instead of a microtask?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview