JavaScript Event Loop Interview Pattern: Async Code Execution

Most mid-senior frontend interviews now love going beyond "what is the event loop?" and instead test whether you can predict how JavaScript actually executes async code. Here's a pattern you should be 100% comfortable with (and able to explain on a whiteboard): console.log("A"); setTimeout(() => {  console.log("B"); }, 0); Promise.resolve().then(() => {  console.log("C"); }); console.log("D"); Expected output order: A D C B If you only remember "setTimeout is async", this question will trick you. The key is understanding: - JavaScript has a single call stack, but multiple queues. - Promise callbacks go to the microtask queue, which is drained BEFORE the macrotask queue (where setTimeout lives). In an interview, do not just say "microtasks vs macrotasks". Walk through it step-by-step: 1. console.log("A") runs immediately. 2. setTimeout schedules "B" in the macrotask queue. 3. Promise.resolve().then schedules "C" in the microtask queue. 4. console.log("D") runs. 5. Call stack is empty → microtasks run → logs "C". 6. Then macrotask queue runs → logs "B". If you can confidently reason about this, you're already ahead for questions on: - Debouncing/throttling behavior. - React concurrent rendering edge cases. - Performance bugs caused by heavy microtask usage. Next time you see a nested mix of setTimeout, Promise, async/await, and event handlers in an interview, don't panic — treat it as an event-loop trace exercise. Comment "event loop++" if you want me to break down a tougher event-loop + React/Next.js example with multiple promises and timeouts! #frontend #javascript #eventloop #webdevelopment #frontendinterview #reactjs #nextjs #asyncjavascript

To view or add a comment, sign in

Explore content categories