JavaScript Event Loop: Call Stack, Web APIs, and Microtasks Explained

📌 I went deep into the JavaScript Event Loop. Here's what you need to know — JavaScript is single-threaded. One thing at a time. So how does it handle API calls, timers, and clicks without freezing? That's the Event Loop. 🏗️ 4 pieces working together: ✅ Call Stack Queue — where code runs. LIFO. One function at a time. ✅ Web APIs Queue — browser handles slow work here. setTimeout, fetch, DOM events — all offloaded outside the JS engine. ✅ Microtask Call Stack Queue — Promise callbacks (.then, async/await). Fully drained before anything else moves. ✅ Macrotask Call Stack Queue — setTimeout, setInterval, I/O. One item per loop cycle. 🔄 Exact priority order — on repeat: -Run the Call Stack Queue -Drain ALL Microtasks -Pick ONE Macrotask -Drain ALL Microtasks again -Repeat ⚡ Why this output surprises people: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")).then(() => console.log("4")); console.log("5"); // Output: 1 → 5 → 3 → 4 → 2 Sync runs first. Microtasks before macrotasks. setTimeout runs last — even at 0ms. This one example covers 80% of interview questions on this topic. 🔬 async/await = Promises underneath async function run() { console.log("A"); await Promise.resolve(); console.log("B"); // Microtask Call Stack Queue } console.log("1"); run(); console.log("2"); // Output: 1 → A → 2 → B Every await pushes the rest of the function into the Microtask Call Stack Queue. ❌ Blocking the Call Stack Queue: while (Date.now() - start < 3000) {} // freezes everything No timers. No clicks. No UI. This is why heavy work belongs in a Web Worker. 🎤 Interview questions — answer these yourself: 1. What is the Event Loop and why does JS need it? 2. Microtask vs Macrotask Call Stack Queue — what's the difference? 3. Why doesn't setTimeout(0) run immediately? 4. Can the Microtask Queue starve the Macrotask Queue? 5. How does async/await relate to the Microtask Queue internally? 6. Where does browser rendering fit in the Event Loop cycle? 🧩 The mental model I keep coming back to: Think of a restaurant kitchen. 🔺 The chef is the Call Stack Queue — cooks one dish at a time, nothing else. 🔺 The oven and timers are the Web APIs Queue — working quietly in the background. 🔺 Urgent verbal orders are the Microtask Call Stack Queue — handled completely between every single dish. 🔺 New tickets from the front of house are the Macrotask Call Stack Queue — come in one at a time, wait their turn. 🔺 The expeditor is the Event Loop — constantly checking all queues and keeping everything moving in the right order. 🔺 The chef never picks up a new ticket until every urgent verbal order is handled first. Drop your answer to Q4 below - #JavaScript #EventLoop #CallStackQueue #Frontend #JSInterviews #LearnInPublic #webdevelopment #interviewprep

To view or add a comment, sign in

Explore content categories