Microtasks vs Macrotasks

JavaScript executes tasks in an event loop, which manages two main types of tasks: macrotasks and microtasks. Understanding the difference helps predict the order in which asynchronous code runs.

Illustration of Microtasks vs Macrotasks
Illustration of Microtasks vs Macrotasks
Comparison: Microtasks vs Macrotasks
AspectMicrotasksMacrotasks
ExamplesPromises (.then, async/await), MutationObserver callbackssetTimeout, setInterval, I/O events, UI rendering
Execution timingRun immediately after the currently executing script and before renderingRun after microtasks and rendering, one at a time
QueueSingle queue, tasks run until empty before moving onSeparate queue, one task per event loop iteration
ImpactCan delay rendering if heavy or many microtasksControls when browser can update UI and process input

💡 Why It Matters

Microtasks run before the browser repaints, so they can update state or DOM immediately after the current code but before the screen updates. Macrotasks allow the browser to interleave rendering and user input with script execution.

Here is the typical event loop order simplified:

  • Execute current script (synchronous code)
  • Run all microtasks (Promise resolutions, MutationObserver)
  • Render updates to the screen
  • Run one macrotask (e.g., setTimeout callback)
  • Repeat

📌 Deep Dive: Execution Order Example

JAVASCRIPT
console.log('script start');

setTimeout(() => {
  console.log('setTimeout macrotask');
}, 0);

Promise.resolve().then(() => {
  console.log('promise microtask');
});

console.log('script end');
Output
script start
script end
promise microtask
setTimeout macrotask

💡 Key Insight

Promises (microtasks) always run before setTimeout callbacks (macrotasks), even if the timeout is zero.

⚠️ Beware of Long Microtask Queues

Heavy or infinite microtask loops can starve the browser from rendering or processing user input, causing UI freezes.

To summarize:

  • Microtasks execute immediately after the current synchronous code, before the browser updates the UI.
  • Macrotasks run after microtasks and rendering, allowing the event loop to process other events.