Hiprup

What is queueMicrotask?

queueMicrotask schedules a function to run as a microtask — after the current synchronous code, but before any timers.

  • Timing — runs in the microtask queue, like Promise callbacks, ahead of setTimeout.

  • Use — defer work to right after the current task without a full timer delay.

Choose it over setTimeout(…, 0) when you need to run as soon as possible, but after the current code finishes.

console.log('1: sync');

setTimeout(() => console.log('2: macrotask'), 0);

queueMicrotask(() => console.log('3: microtask'));

Promise.resolve().then(() => console.log('4: microtask (promise)'));

console.log('5: sync');

// Output: 1, 5, 3, 4, 2
// Sync first, then ALL microtasks, then macrotask

Sync code runs first (1, 5). Then ALL microtasks drain: queueMicrotask (3) and Promise.then (4) — both are microtasks at the same priority.

Then macrotask: setTimeout (2). queueMicrotask is a lower-level API than Promise.then for scheduling microtasks.

queueMicrotask has the same priority as Promise.then — both are microtasks. It runs after sync code but before setTimeout.

Show the output order (sync → microtasks → macrotask). It is a cleaner way to schedule microtasks than creating a Promise just for its .then.