Careeroza
Microtasks vs Macrotasks
Two Queues
| Queue | Filled by | Runs |
|---|---|---|
| Microtasks | promise callbacks, await continuations, queueMicrotask | all of them, right after the current script/task |
| Macrotasks (tasks) | setTimeout, setInterval, I/O, UI events | one per event-loop turn |
Tricky Ordering
Example
console.log("1 sync");
setTimeout(() => {
console.log("6 timeout");
Promise.resolve().then(() => console.log("7 microtask inside timeout"));
}, 0);
(async () => {
console.log("2 async function body runs synchronously");
await null;
console.log("4 after await (microtask)");
})();
Promise.resolve().then(() => console.log("5 promise then"));
console.log("3 sync end");Output
1 sync 2 async function body runs synchronously 3 sync end 4 after await (microtask) 5 promise then 6 timeout 7 microtask inside timeout
Note: Infinite microtasks (a promise callback that schedules another forever) block rendering and timers completely.