Lesson 1 of 9 · 24m
The Event Loop: Tasks and Microtasks
The two-queue model behind JavaScript scheduling — why promise callbacks beat timers, and how to predict ordering before running the code.
The most expensive JavaScript misconception is that async callbacks form one big FIFO queue. They do not. The runtime has macrotasks (usually just called tasks) such as script evaluation, timers, I/O events, and setTimeout, plus a microtask queue for promise reactions, queueMicrotask, and MutationObserver callbacks. After every task, the engine drains the entire microtask queue before moving on.
That one sentence explains most scheduling mysteries in production.
The rule you can run in your head
console.log("script");
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("end");Output:
script
end
promise
timeoutThe script itself is one task. Synchronous statements finish first. When the stack unwinds, the engine drains microtasks, so the promise reaction runs. Only then may it take the next task — the timeout callback.
Microtasks can starve the loop
Because the queue is drained completely, a microtask that schedules another microtask can run forever while timers, input, rendering, and I/O wait:
function loop() {
Promise.resolve().then(loop);
}
loop(); // the page never gets another taskThis is worse than a busy while loop in one respect: it does not look like synchronous blocking in the code that caused it. The tab freezes because the microtask checkpoint never ends.
Where async/await fits
await is not magic and it is not a thread switch. It splits your function at the await point and queues the continuation as a promise reaction:
async function load() {
console.log("before");
await null;
console.log("after"); // microtask, not synchronous
}
load();
console.log("outside");The output is before, outside, after. Even await null yields. If a profiler shows state changing "between two adjacent lines," this is usually why.
A practical ordering model
For one turn of the loop:
- Execute the current task until the call stack is empty.
- Drain the microtask queue completely, including microtasks queued while draining.
- In browsers, perform rendering steps when needed.
- Pick the next eligible task.
Node and browsers differ in which task sources exist (process.nextTick, setImmediate, message events), but the task/microtask split survives everywhere.
Field notes
setTimeout(fn, 0)does not mean "now"; it means "a future task, after clamping and scheduling."- Promise resolution order is reliable. Reliance on timer order under load is not.
- If rendering must happen before expensive work, yielding with a task (
setTimeout) is different from yielding with a microtask. process.nextTickin Node runs before promise microtasks and can starve the loop even more aggressively. Treat it as a specialist tool.
Was this lesson helpful?