Event Loop
JavaScript is single-threaded - it can only do one thing at a time. The event loop is the mechanism that handles asynchronous operations.
Components
text
┌─────────────────────────────────┐
│ Call Stack │ <- executes synchronous code
├─────────────────────────────────┤
│ Microtask Queue │ <- Promise callbacks, queueMicrotask
├─────────────────────────────────┤
│ Macrotask Queue │ <- setTimeout, setInterval, I/O
└─────────────────────────────────┘Order of execution
- Run all synchronous code (call stack).
- Run all microtasks (Promise
.then,queueMicrotask). - Run one macrotask (setTimeout, setInterval).
- Repeat from step 2.
Example
js
console.log('1 - sync');
setTimeout(() => console.log('2 - macrotask'), 0);
Promise.resolve().then(() => console.log('3 - microtask'));
console.log('4 - sync');
// Output:
// 1 - sync
// 4 - sync
// 3 - microtask
// 2 - macrotaskWhy microtasks come first
js
Promise.resolve()
.then(() => console.log('micro 1'))
.then(() => console.log('micro 2'));
setTimeout(() => console.log('macro'), 0);
// micro 1 -> micro 2 -> macro
// ALL microtasks drain before any macrotask runsUnderstanding the event loop is critical for debugging timing bugs, infinite loops in Promises, and understanding why
setTimeout(fn, 0)doesn't mean "run immediately".
updated
did you know it?