Microtasks and macrotasks in JavaScript
Promises jump the queue: every microtask runs before the next timer.
console.log("1 synchronous");
setTimeout(() => console.log("5 timeout"), 0);
Promise.resolve().then(() => console.log("3 microtask"));
queueMicrotask(() => console.log("4 queueMicrotask"));
console.log("2 synchronous end");
// prints 1, 2, 3, 4, 5 -- the timer is last even at zero delay
How it works
- Synchronous code finishes first, always.
- Then the microtask queue drains: promises and queueMicrotask.
- Only then does a timer callback get its turn.
Keywords and builtins used here
Promise
The run, in numbers
- Lines
- 10
- Characters to type
- 291
- Tokens
- 62
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 35 seconds.
Step 1 of 3 in Scheduling, step 12 of 19 in Promises & async.