🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript Microtasks and Macrotasks

A microtask is a small job that runs before the next timer. Promise handlers are microtasks, and the microtask queue runs first.

A promise beats a timer

The promise handler is a microtask. The timer callback is a macrotask, so it runs after the microtask.

console.log("One");
Promise.resolve().then(() => { console.log("Promise handler"); });
setTimeout(() => { console.log("Timer"); }, 0);
console.log("Two");

queueMicrotask directly

queueMicrotask adds one job to the microtask queue. The job runs after the main script and before any timer.

console.log("Start");
queueMicrotask(() => { console.log("Microtask"); });
console.log("End");

Microtasks keep their order

Microtasks run in the order they were added. Both run before the timer callback.

Promise.resolve().then(() => { console.log("First microtask"); });
queueMicrotask(() => { console.log("Second microtask"); });
setTimeout(() => { console.log("Timer"); }, 0);
console.log("Sync");

Example

console.log("Begin");
Promise.resolve("Done").then((value) => { console.log(value); });
setTimeout(() => { console.log("Timer last"); }, 0);
console.log("Finish");

Key points

  • Microtask: a small job that runs right after the current script finishes
  • Macrotask: a larger job like a timer callback, which waits for the microtask queue to clear
  • Promise handlers are microtasks.
  • The microtask queue runs to empty before the next macrotask starts.
  • queueMicrotask: a function that adds one job to the microtask queue
  • A microtask that adds another microtask runs before any timer.

In this example, the first line prints Begin. The promise handler is a microtask, so it prints Done before the timer. The last line prints Finish before either queued job runs.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

Which runs first after the main script finishes?