Module 26 // Core JavaScript

Microtasks & queueMicrotask

Module Objective

Promise jobs, scheduling guarantees vs macrotasks

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Priority Order
console.log("1. Stack");

setTimeout(() => console.log("2. Macrotask"), 0);

Promise.resolve().then(() => {
  console.log("3. Microtask");
});

console.log("4. Stack");

// Output: 1, 4, 3, 2
💡 Stack code runs first. Then, the engine clears the *entire* Microtask queue. Only after that does it pick up the first Macrotask from the Task Queue.
// Example 2
// 2. Microtask Starvation (Danger!)
function starve() {
  Promise.resolve().then(starve);
}
// starve(); // ❌ Don't run this!
💡 Because the Event Loop won't move to the next macrotask (or render the UI) until the Microtask queue is empty, an infinite loop of microtasks will completely freeze your browser tab.
// Example 3
// 3. queueMicrotask vs .then
// This is useful for running logic after state changes
// but before the browser paints the screen.
queueMicrotask(() => {
  console.log("Cleanup before paint");
});
💡 `queueMicrotask` is a standard way to schedule work to happen at the very end of the current task.

Engine & Memory Architecture

Queue Internals

1. Microtask Queue:

  • A dedicated queue in the engine's memory.
  • It is processed completely at the end of every task.

2. Task Queue (Macrotasks):

  • Handled by the Event Loop.
  • Only one macrotask is processed per loop iteration.

3. Rendering:

  • The browser tries to re-render the screen after the Microtask queue is empty and before the next Macrotask.
  • Performance: Heavy microtasks can delay the "Frame Paint," leading to a stuttery UI.