JavaScriptFundamental (ES6), part 1
Event loop order: microtasks vs macrotasks in JavaScript
141 the order the event loop really runs things in
hardIn one script, log a label synchronously, register a Promise.resolve().then, a queueMicrotask, an async function that awaits, and a setTimeout(fn, 0). Record the order they actually run in, not the order you wrote them. Then prove three follow-ups: queueMicrotask and .then share one queue, two promise chains advance one link each per turn, and a microtask queued from inside a microtask still beats the timer.
Stuck? Three hints, smallest first
- 1. Push labels into an array instead of printing them, and take a copy of that array before you await anything.
- 2. The whole microtask queue is drained before the loop looks at a single macrotask, and a
setTimeoutcallback is a macrotask. - 3. An
asyncfunction body up to its firstawaitis ordinary synchronous code. Theawaitis the part that queues a microtask.
const order = [];
const log = (label) => order.push(label);
let releaseTimer;
const timerRan = new Promise((resolve) => { releaseTimer = resolve; });
log('1 script top');
setTimeout(() => { log('7 setTimeout 0'); releaseTimer(); }, 0);
Promise.resolve().then(() => log('4 promise.then'));
queueMicrotask(() => log('5 queueMicrotask'));
const tally = async () => {
log('2 async body, before the first await');
await null;
log('6 async body, after the await');
};
tally();
log('3 script bottom');
const beforeAnythingAsync = [...order];
await timerRan;
const everything = [...order];
const timerCameLast = everything[everything.length - 1] === '7 setTimeout 0';
// One queue, not two: they interleave by registration order.
const sharedQueue = [];
queueMicrotask(() => sharedQueue.push('micro 1'));
Promise.resolve().then(() => sharedQueue.push('then 1'));
queueMicrotask(() => sharedQueue.push('micro 2'));
Promise.resolve().then(() => sharedQueue.push('then 2'));
await new Promise((resolve) => queueMicrotask(resolve));
// Each .then is one microtask, so two chains advance in lockstep.
const chain = [];
const chainA = Promise.resolve()
.then(() => { chain.push('A1'); })
.then(() => { chain.push('A2'); })
.then(() => { chain.push('A3'); });
const chainB = Promise.resolve()
.then(() => { chain.push('B1'); })
.then(() => { chain.push('B2'); })
.then(() => { chain.push('B3'); });
await Promise.all([chainA, chainB]);
// A microtask can add to the queue it is being drained from.
const nested = [];
let releaseSecond;
const secondTimer = new Promise((resolve) => { releaseSecond = resolve; });
setTimeout(() => { nested.push('timer'); releaseSecond(); }, 0);
Promise.resolve().then(() => {
nested.push('microtask');
Promise.resolve().then(() => nested.push('microtask queued from a microtask'));
});
await secondTimer;
console.log('sync only :', beforeAnythingAsync);
console.log('everything:', everything);
console.log('one queue :', sharedQueue);
console.log('two chains:', chain);
console.log('nested :', nested);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('while the script is still running, nothing asynchronous has happened', beforeAnythingAsync, ['1 script top', '2 async body, before the first await', '3 script bottom']);
test('an async body up to its first await is plain synchronous code', beforeAnythingAsync[1], '2 async body, before the first await');
test('the real order, in full', everything, ['1 script top', '2 async body, before the first await', '3 script bottom', '4 promise.then', '5 queueMicrotask', '6 async body, after the await', '7 setTimeout 0']);
test('so every microtask ran before the single macrotask', [timerCameLast, everything.length], [true, 7]);
test('queueMicrotask and .then feed one queue, drained in registration order', sharedQueue, ['micro 1', 'then 1', 'micro 2', 'then 2']);
test('which is why two chains advance one link each per turn', chain, ['A1', 'B1', 'A2', 'B2', 'A3', 'B3']);
test('a microtask queued from a microtask is drained in the same turn', nested, ['microtask', 'microtask queued from a microtask', 'timer']);
test('and the timer waited for both of them', nested.indexOf('timer'), 2);
One turn of the loop is: run the current job to completion, then drain the entire microtask queue, then take one macrotask. That single sentence predicts every line above. The labels are numbered in the order they run, and reading the source top to bottom gives 1, 7, 4, 5, 2, 6, 3 — which is why guessing does not work.
queueMicrotask and promise reactions are not separate lanes; they are one FIFO queue, so ordering between them is decided purely by when each was registered. A .then chain therefore cannot run three links in one go: each link is one microtask, and the queue is fair, so a second chain gets a turn between every link. That is the mechanism behind the A1, B1, A2, B2 pattern.
The last two assertions are the dangerous ones. A microtask may queue more microtasks, and they are drained in the same pass, so an unbounded chain of .then calls starves the macrotask queue for ever: timers never fire, rendering never happens, the tab appears frozen with no busy loop anywhere. setTimeout(fn, 0) is the escape hatch precisely because it is a macrotask, and that is also why 0 never means now.