JavaScript Event Loop: Sync, Microtasks, Macrotasks Explained

🔄 The Event Loop: How JavaScript Really Works 80% of candidates fail this. Don't be one of them. The Classic Test: ```js console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4'); ``` Output: 1, 4, 3, 2 --- ⚙️ How It Works Step 1: Call Stack runs sync code → 1 and 4 log. Step 2: Web APIs handle async operations while stack clears. Step 3: Event Loop checks queues in priority: ``` 1. Run ALL sync code 2. Clear ENTIRE Microtask Queue (Promises) 3. Run ONE Macrotask (setTimeout) 4. Repeat ``` Queue Examples Priority Microtasks Promises, queueMicrotask 🔥 Highest Macrotasks setTimeout, events, I/O ⬇️ Lower Why output is 1, 4, 3, 2: · Sync: 1, 4 log immediately · Microtask queue: 3 logs (all microtasks run) · Macrotask queue: 2 logs (one runs next) --- 🚨 Critical Rules ✅ Microtasks ALWAYS run before next macrotask — even with 0ms delay. ✅ Microtasks queuing microtasks? They ALL run in same cycle. ✅ Too many microtasks = UI freeze (macrotasks never run). --- 🔥 Common Questions Q: Will this log "DONE"? ```js while (true) { Promise.resolve().then(() => {}); } console.log('DONE'); ``` A: No — microtasks starve the loop forever. Q: Async/await order? ```js async function test() { console.log('A'); await Promise.resolve(); console.log('B'); } test(); console.log('C'); ``` A: A, C, B — await schedules rest as microtask. Q: 10,000 microtasks + 1 macrotask? A: All microtasks run first → page freezes. Fix: Use Web Workers or chunk work. --- 💡 Senior Takeaway Event loop knowledge = better performance: · Batch DOM updates in microtasks · Break heavy loops with setTimeout · Understand React effect scheduling --- 👇 Your turn: Write code with sync + microtask + macrotask. Post output below. #JavaScript #EventLoop #AsyncJS #FrontendInterview #WebPerformance

To view or add a comment, sign in

Explore content categories