Execution Order
Synchronous code | Runs first, on the call stack |
Microtasks (Promise.then, queueMicrotask) | Run after each task, before rendering |
Macrotasks (setTimeout, setInterval, I/O) | Run next task after microtasks drain |
Rendering / animation frames | Between task/microtask processing |
Examples
console.log('1');
setTimeout(() => console.log('3'), 0);
Promise.resolve().then(() => console.log('2'));
console.log('4') | Output: 1, 4, 2, 3 |
async function f() {
console.log('a');
await Promise.resolve();
console.log('b');
} | 'a' sync, 'b' in microtask |
Web APIs
setTimeout(fn, 0) | Schedule macrotask (min ~4ms in browser) |
queueMicrotask(fn) | Queue microtask |
requestAnimationFrame(fn) | Before next paint |
MessageChannel | High-priority macrotask |