Intermediate LevelJavaScript & TypeScript
Explain the JavaScript Event Loop, microtasks, and macrotasks.
❓ Interview Prompt: Describe the event loop execution model, microtask queue (Promise.then), macrotask queue (setTimeout), and rendering timing.
JavaScript is single-threaded with an event loop that processes tasks from multiple queues:
Execution Order:
1
Execute current synchronous code on the Call Stack.
2
Process ALL pending Microtasks (Promise.then, queueMicrotask, MutationObserver).
3
Perform Rendering (layout, paint) if needed.
4
Pick ONE Macrotask (setTimeout, setInterval, I/O callbacks, UI events) and execute it.
5
Repeat from step 2.
Key Insight:
Microtasks always run before the next macrotask. If you keep queueing microtasks, macrotasks and rendering are starved.
Code Implementation Example
javascript
console.log('1: Sync');
setTimeout(() => console.log('2: Macrotask'), 0);
Promise.resolve().then(() => console.log('3: Microtask'));
queueMicrotask(() => console.log('4: Microtask 2'));
console.log('5: Sync');
// Output order:
// 1: Sync
// 5: Sync
// 3: Microtask
// 4: Microtask 2
// 2: Macrotask💡Execution order demonstrating microtask priority over macrotasks.
🎯 Interview Key Takeaway
Microtasks (Promises) always execute before macrotasks (setTimeout) and before the next rendering frame.
#Event Loop#Microtasks#Macrotasks#Intermediate
Back to all JavaScript & TypeScript Questions→