TypeScript/Async/Lesson 02
Event Loop — Microtask vs Macrotask, Expressing Queues with Types
30 min·theory
This chapter
2/7
TypeScript
Event Loop — Microtask vs Macrotask, Expressing Queues with Types
💡 Why Should You Learn This? — See the Queue, See the Bug
🎯
Why Promise executes before setTimeout: the microtask queue takes priority over the macrotask queue. A classic interview question.
💼
TypeScript does not change the queues themselves, but it can enforce the signatures of functions placed into those queues. Mistakes such as passing the wrong callback are caught at compile time before they ever enter the queue.
⚡
TypeScript knows the exact callback signatures for `queueMicrotask`, `setImmediate`, and `requestAnimationFrame`, which prevents incorrect call patterns.
🔗
Ordering bugs in asynchronous code (race conditions) cannot be caught by the type system — but understanding the queue model is prerequisite to debugging them.
🏢 실무에서는
React's `useEffect`, Next.js's `useTransition`, Vue's `nextTick` — all of them sit on top of the microtask/macrotask queue model. Why you get a stale value when you read the DOM immediately after `setState`, and why props can change between two `await` lines — it all comes down to the event loop model.
Call Stack → Web API → Queue → Loop
1. The 4 Components of the Event Loop
2. One Cycle of the Loop
1. When the Call Stack is empty, drain the entire Microtask Queue.
2. Then pull exactly one item from the Macrotask Queue.
3. Drain the Microtask Queue again.
4. Repeat.
3. What TypeScript Protects
4. Where async/await Meets the Queue
💡 💡 Event Loop Interview Classics + Mistakes TypeScript Catches
1. Why Promise runs before setTimeout(0)
Microtask queue priority: within a single cycle, all microtasks are drained before one macrotask is processed.
2. Code after await is always a microtask
3. queueMicrotask callbacks take no arguments — TypeScript enforces this
4. TypeScript knows about setTimeout's extra arguments
5. An infinite microtask loop freezes the main thread
TypeScript cannot catch this — block it in code review.
⚡ Try It Yourself — Event Loop Order
Verify the order: sync → microtask → macrotask with your own eyes.
✏️ JS 코드
📟 Console output
▶ Press the Run button
⚠️ Runs in a browser sandbox — only console.log() is supported; alert/fetch are not.
Check Your Understanding
What is the output order of the following code?
```ts
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C'));
console.log('D');
```
Read this first: Synchronous vs. Asynchronous — Protecting Callback Signatures
Up next: Promise<T> — JS vs TS Differences