JavaScript Event Loop Explained

JavaScript Event Loop JavaScript uses an event-driven, non-blocking I/O model to handle async operations—even though it runs on a single thread. This is made possible by 3 core components: 1. Call Stack (Execution Context Stack) A LIFO stack (Last In, First Out) that executes functions Every function call creates an execution context and is pushed onto the stack When execution completes, it is popped off If the stack is busy, nothing else can run 2. Queues (Where async tasks wait) Microtask Queue (High Priority) Runs immediately after current code finishes Always executed before macrotasks Includes: Promise.then() catch, finally queueMicrotask() Callback Queue / Macrotask Queue (Normal Priority) Runs after microtasks are completed Executes one task per event loop cycle Includes: setTimeout setInterval DOM events I/O callbacks Key Difference (Micro vs Macro) Microtasks Macrotasks High priority Lower priority Run all at once Run one at a time After sync code After microtasks Example: Promises Example: setTimeout 3. Event Loop (Core Scheduler) The event loop continuously checks: “Is the Call Stack empty?” If YES: 1. Run ALL Microtasks 2. Run ONE Macrotask 3. Repeat Execution Example console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); Step-by-Step Execution "Start" → executed (sync) setTimeout → goes to macrotask queue Promise.then → goes to microtask queue "End" → executed (sync) Call Stack becomes empty Event Loop Action Run all microtasks → "Promise" Run one macrotask → "Timeout" Final Output Start End Promise Timeout Important Technical Points ✔ JavaScript runtime = Call Stack + Heap + Event Loop + Queues ✔ Microtasks always execute before macrotasks ✔ Rendering happens after microtasks (browser behavior) ✔ Long sync code blocks everything (event loop freeze) One-Line Summary Event Loop = Scheduler that runs microtasks first, then macrotasks, ensuring non-blocking execution #JavaScript #EventLoop #AsyncJS #WebDevelopment #Frontend #Programming #TechDeepDive

  • diagram

To view or add a comment, sign in

Explore content categories