JS Microtasks vs Macrotasks: A Complete Guide

Understand the difference between JavaScript microtasks and macrotasks. Learn the exact execution order, which APIs use each queue, starvation risks, and how to use queueMicrotask correctly.

JavaScriptintermediate
11 min read

The JavaScript event loop has two distinct queues for deferred callbacks: the microtask queue and the macrotask queue (also called the task queue). They differ in priority and timing. Microtasks run after every task and before any rendering. Macrotasks run one per event loop iteration. Knowing which queue an API uses determines exactly when your code runs.

The Two Queues

javascriptjavascript
// Microtask example: Promise.then
Promise.resolve().then(() => console.log("Microtask"));
 
// Macrotask example: setTimeout
setTimeout(() => console.log("Macrotask"), 0);
 
console.log("Synchronous");
 
// Output:
// Synchronous
// Microtask   <-- Always before macrotask
// Macrotask

The rule: microtasks run to completion after the current task finishes, before the next macrotask starts.

Complete API Classification

APIQueue Type
Promise.then() / .catch() / .finally()Microtask
async/await continuation (after await)Microtask
queueMicrotask(fn)Microtask
MutationObserver callbackMicrotask
IntersectionObserver callbackTask (rendering step)
setTimeout(fn, N)Macrotask
setInterval(fn, N)Macrotask
DOM event handlers (click, keydown, etc.)Macrotask
MessageChannel.postMessageMacrotask
requestAnimationFramePre-render (between tasks)
setImmediate (Node.js)Check phase (after I/O)
process.nextTick (Node.js)Before microtasks!

Execution Order Drill

javascriptjavascript
console.log("1");
 
setTimeout(() => console.log("2: setTimeout"), 0);
 
Promise.resolve()
  .then(() => {
    console.log("3: Promise 1");
    return Promise.resolve(); // Wrapping in a resolved promise adds another microtask tick
  })
  .then(() => console.log("4: Promise 2"));
 
queueMicrotask(() => console.log("5: queueMicrotask"));
 
setTimeout(() => console.log("6: setTimeout 2"), 0);
 
console.log("7");
 
// Output:
// 1
// 7
// 3: Promise 1      (microtask)
// 5: queueMicrotask (microtask)
// 4: Promise 2      (microtask -- added when Promise 1's then resolved)
// 2: setTimeout     (macrotask -- first task)
// 6: setTimeout 2   (macrotask -- second task, next iteration)

How Microtasks Drain

After every task (macrotask) completes, the event loop processes all queued microtasks — and any microtasks they add — before moving on:

javascriptjavascript
// Task: synchronous script
console.log("Task start");
 
Promise.resolve()
  .then(() => {
    console.log("Microtask 1");
    Promise.resolve().then(() => {
      console.log("Microtask 1.1 (added during drain)");
      Promise.resolve().then(() => {
        console.log("Microtask 1.1.1 (nested further)");
      });
    });
  });
 
Promise.resolve().then(() => console.log("Microtask 2"));
 
console.log("Task end");
 
// Output:
// Task start
// Task end
// Microtask 1
// Microtask 2          (parallel microtask, runs after Microtask 1)
// Microtask 1.1        (added by Microtask 1, runs before any macrotask)
// Microtask 1.1.1      (added by Microtask 1.1)
// (only NOW would a setTimeout callback run)

The Starvation Problem

Since microtasks drain completely before any macrotask runs, an infinite chain of microtasks starves macrotasks (and rendering):

javascriptjavascript
// DANGEROUS: Infinite microtask chain
function addInfiniteMicrotasks() {
  Promise.resolve().then(addInfiniteMicrotasks);
}
addInfiniteMicrotasks();
// setTimeout NEVER fires:
setTimeout(() => console.log("Never"), 0);
// Page never re-renders (if in browser)

Compare with infinite macrotasks — each setTimeout still yields to rendering and other tasks:

javascriptjavascript
// NOT dangerous (but still burns CPU)
function scheduleMacrotask() {
  setTimeout(scheduleMacrotask, 0);
}
scheduleMacrotask();
// Page CAN re-render between each task iteration

queueMicrotask

queueMicrotask(fn) is a direct way to schedule a microtask without creating a Promise:

javascriptjavascript
// Similar behavior, different APIs:
queueMicrotask(() => console.log("Via queueMicrotask"));
Promise.resolve().then(() => console.log("Via Promise.resolve()"));
 
// Both run as microtasks in definition order:
// "Via queueMicrotask"
// "Via Promise.resolve()"

When to Use queueMicrotask

javascriptjavascript
// Use case: Defer a callback to after current sync code without creating a Promise
class EventEmitter {
  constructor() {
    this.listeners = new Map();
    this._pendingEvents = [];
  }
 
  emit(event, data) {
    const handlers = this.listeners.get(event) || [];
 
    // Queue all handlers as microtasks
    // They run after current sync code but before any macrotask
    handlers.forEach((handler) => {
      queueMicrotask(() => handler(data));
    });
  }
 
  on(event, handler) {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, []);
    }
    this.listeners.get(event).push(handler);
  }
}
 
const emitter = new EventEmitter();
emitter.on("data", (d) => console.log("Handler:", d));
emitter.emit("data", 42);
console.log("After emit");
 
// Output:
// After emit
// Handler: 42

async/await and Microtasks

Each await in an async function creates exactly one microtask handoff. The code after await is a microtask continuation:

javascriptjavascript
async function a() {
  console.log("a start");
  await Promise.resolve(); // Yield -- continuation is a microtask
  console.log("a after await");
}
 
async function b() {
  console.log("b start");
  await Promise.resolve(); // Yield
  console.log("b after await");
}
 
a();
b();
console.log("sync");
 
// Output:
// a start
// b start
// sync
// a after await   (a resumed first, since it awaited first)
// b after await

Multiple Awaits

javascriptjavascript
async function multi() {
  console.log("1");
  await null; // One microtask tick
  console.log("3");
  await null; // Another microtask tick
  console.log("5");
}
 
multi(); // Starts synchronously
console.log("2"); // Sync code runs before async continuations
 
setTimeout(() => console.log("6 (task)"), 0); // Macrotask
 
Promise.resolve().then(() => console.log("4 (microtask)"));
 
// Output: 1, 2, 3, 4, 5, 6
// 1: multi() starts sync
// 2: sync continues
// 3: first await resolves (microtask)
// 4: queueing microtask runs
// 5: second await resolves (microtask)
// 6: setTimeout fires (macrotask)

Practical Implication: UI Batching

Because microtasks run before rendering, you can make multiple DOM mutations in microtasks and they all appear in one frame:

javascriptjavascript
// Both mutations happen before the browser repaints
Promise.resolve()
  .then(() => {
    element.style.opacity = "0";
    element.style.transform = "translateY(-10px)";
  })
  .then(() => {
    // Still a microtask -- still before render
    element.classList.add("hidden");
  });
 
// Browser renders once after both microtasks finish

Comparison: Promise vs setTimeout Timing

javascriptjavascript
function timedComparison() {
  const results = [];
 
  setTimeout(() => results.push("setTimeout"), 0);
  Promise.resolve().then(() => results.push("Promise.then"));
  queueMicrotask(() => results.push("queueMicrotask"));
 
  // At this point, synchronous code is done
  // Microtask queue will drain first, then setTimeout fires
 
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(results);
    }, 10);
  });
}
 
timedComparison().then((r) => console.log(r));
// ["Promise.then", "queueMicrotask", "setTimeout"]
Rune AI

Rune AI

Key Insights

  • Microtasks always run before macrotasks: After any synchronous code or macrotask finishes, ALL microtasks drain before the next macrotask starts
  • Promise.then and queueMicrotask are microtasks: They are guaranteed to run before any setTimeout or setInterval callback regardless of timing
  • Microtask chains run to completion: Adding new microtasks during the drain phase extends the drain — they all run before any macrotask
  • Infinite microtask loops are fatal: An unbreakable chain of Promises blocks macrotasks and rendering until the tab freezes
  • async/await is microtask-powered: Each await handoff is one microtask; code after await resumes before any pending macrotask
RunePowered by Rune AI

Frequently Asked Questions

Why do Promise callbacks run before setTimeout even with the same delay?

Promises use the microtask queue, which is processed completely after every task before the event loop picks the next macrotask. `setTimeout` adds to the macrotask queue. Even `setTimeout(fn, 0)` waits for a full loop iteration. The [event loop](/tutorials/programming-languages/javascript/the-javascript-event-loop-explained-in-detail) always drains all microtasks first to provide consistent, predictable behavior for async control flow.

Can I control which microtasks run first?

Yes. Microtasks run in FIFO (First In, First Out) order within the same queue. The first `Promise.resolve().then()` or `queueMicrotask()` call registered runs first. However, a resolved Promise's `.then()` might take an extra microtask tick compared to `queueMicrotask` depending on how the engine implements Promise resolution internally.

What is process.nextTick in Node.js and how does it differ?

`process.nextTick(fn)` in Node.js runs the callback before the microtask queue processes. It is not part of the Event Loop spec but rather a Node.js-specific queue that runs even before Promise callbacks. Use `queueMicrotask` for portable code that should work the same in browsers and Node.js.

Are there situations where a microtask runs after a macrotask?

Yes, when a macrotask schedules a microtask, that microtask runs after the macrotask finishes but before the next macrotask. For example: a `setTimeout` callback that calls `Promise.resolve().then(fn)` — `fn` runs as a microtask during the drain phase after the setTimeout callback completes.

Should I prefer queueMicrotask or Promise.resolve().then()?

For scheduling a simple callback as a microtask with no result, `queueMicrotask` is more direct and semantically clearer. `Promise.resolve().then()` is better when you need the result to chain further Promises. Both schedule a microtask, but `queueMicrotask` avoids creating a Promise object, which is slightly more efficient.

Conclusion

FeatureMicrotask QueueMacrotask Queue
APIsPromise, queueMicrotask, MutationObserversetTimeout, setInterval, DOM events
PriorityHigher (runs before macrotasks)Lower (runs one per loop iteration)
Drain behaviorAll microtasks drained before next macrotaskOne task per loop iteration
Can block renderingYes (if infinite chain)No (rendering happens between iterations)
Can cause starvationYes (prevents macrotasks from running)No
Main useShort continuations after async operationsDeferred work, timers, browser events
Microtasks and macrotasks are two queues in the event loop with different priorities. Microtasks (Promises, queueMicrotask) drain completely after every task before any macrotask runs. Macrotasks (setTimeout, setInterval, DOM events) run one at a time per loop iteration. Understanding this order is fundamental to writing correct async JavaScript.