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
JavaScript Event Loop Explained
More Relevant Posts
-
💡 Understanding Closures in JavaScript (Simple & Clear) Closures are one of the most powerful concepts in JavaScript — and also one of the most confusing at first! 👉 A closure is created when a function remembers variables from its outer scope, even after the outer function has finished executing. 🔹 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 👉 Let’s break what’s really happening: • The outer() function runs and creates a variable count • It creates the inner() function • outer() returns inner() (not calling it, just returning it) ⚠️ Normally: When a function finishes execution, its variables are destroyed. ✅ But here: inner() is still using count 👉 So JavaScript keeps count in memory 👉 This preserved memory is called a closure 💡 Important insights: • Functions in JavaScript are first-class (can be returned and stored) • inner() runs later, not inside outer() • It keeps a reference to count, not a copy • That’s why the value updates (1 → 2 → 3) 🔥 Closure in Action (Tricky Example): for (var i = 1; i <= 3; i++) { setTimeout(function() { console.log(i); }, 1000); } 👉 Output: 4 4 4 ❓ Why? • var is function-scoped (only one shared variable i) • Loop finishes first → i becomes 4 • All callbacks use the same i ✅ Fix using let: for (let i = 1; i <= 3; i++) { setTimeout(function() { console.log(i); }, 1000); } 👉 Output: 1 2 3 ✔ Because: • let is block-scoped • Each iteration gets its own i • Each callback closes over a different variable ✅ Why closures are useful: • Data privacy (private variables) • Maintaining state • Used in callbacks and async programming 📌 One-line takeaway: A closure is a function that remembers its outer variables even after the outer function has finished execution. #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode
To view or add a comment, sign in
-
-
💡 JavaScript Essentials: Closures & Hoisting Explained Simply If you're working with JavaScript, especially in frameworks like Angular or React, understanding closures and hoisting is a must. Here’s a quick breakdown 👇 🔹 Closures A closure is created when a function remembers its outer scope even after that outer function has finished execution. 👉 Why it matters? Helps in data encapsulation Used in callbacks, event handlers, and async code Powers concepts like private variables Example: function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 🔹 Hoisting Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 Key points: var is hoisted and initialized with undefined let and const are hoisted but stay in the Temporal Dead Zone Function declarations are fully hoisted Example: console.log(a); // undefined var a = 10; console.log(b); // ReferenceError let b = 20; 🚀 Takeaway Closures help you retain state, while hoisting explains how JavaScript reads your code before execution. Mastering these will level up your debugging skills and help you write cleaner, predictable code. #JavaScript #WebDevelopment #Frontend #Angular #React #Coding #Developers
To view or add a comment, sign in
-
Stop Guessing, Start Mastering: The JavaScript Lifecycle Ever wondered why setTimeout(() => {}, 0) doesn't actually run in 0 milliseconds? Or why your UI freezes during a heavy calculation? Understanding the JavaScript Event Loop is the definitive line between a junior and a senior developer. Here is the breakdown: 1.The Single-Threaded Myth JavaScript is single-threaded (one task at a time), but the Browser/Node environment is multi-threaded. The Reality: The Call Stack handles your immediate code, while Web APIs handle the heavy lifting (network requests, timers) in the background. This keeps the main thread from blocking. 2️.The Priority Hierarchy (VIP vs. Regular) This is where 90% of bugs live. The Event Loop prioritizes queues differently: Microtasks (The VIPs): Promises (.then, async/await) and process.nextTick. The Loop will not move on until this queue is 100% empty. Macrotasks (The Regulars): setTimeout, setInterval, and DOM events. These must wait their turn. 3️.The "Wait" Logic The Event Loop only pushes a task from a queue to the Call Stack if and only if the Stack is empty. The Trap: If you run a massive for loop, your promises and timers will hang indefinitely, no matter how "fast" they are supposed to be. Pro-Tips for the Senior Mindset: Keep the Stack Clean: Never block the main thread with heavy math. Offload it to a Web Worker. Memory Hygiene: The lifecycle ends with Garbage Collection. If you don’t remove event listeners or clear intervals, you’re creating memory leaks. The Golden Rule: Synchronous Code ➔ Microtasks (Promises) ➔ Macrotasks (Timers). Master the loop, master the language. Why this works for your post: The Hook: It starts with a relatable technical paradox (setTimeout 0). Formatting: Uses emojis and bold text to make key terms pop. The "So What?": It explains the consequence (UI freezing/bugs) rather than just the theory. Structure: It follows the logical flow of Execution -> Priority -> Optimization. #JavaScript #WebDevelopment #SoftwareEngineering #Frontend #CodingTips #EventLoop #FullStackDeveloper #Programming
To view or add a comment, sign in
-
-
🔍 JavaScript Bug You Might Have Seen (setTimeout vs Promise) You write this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you expect? Start Timeout Promise End But actual output is: Start End Promise Timeout This happens because of the Event Loop 📌 What is the Event Loop? 👉 The event loop is the mechanism that decides which task runs next in JavaScript’s asynchronous execution. 📌 Priority order (very important): 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue 3️⃣ Macrotask Queue 📌 What’s inside each queue? 👉 Microtask Queue (HIGH priority): ✔ Promise.then / catch / finally ✔ queueMicrotask ✔ MutationObserver 👉 Macrotask Queue (LOWER priority): ✔ setTimeout ✔ setInterval ✔ setImmediate ✔ I/O tasks ✔ UI rendering events Execution flow: ✔ Step 1: Run all synchronous code 👉 Start → End ✔ Step 2: Execute ALL microtasks 👉 Promise ✔ Step 3: Execute macrotasks 👉 setTimeout So final order becomes: Start End Promise Timeout 💡 Takeaway: ✔ Microtasks run before macrotasks ✔ Promises > setTimeout ✔ setTimeout(fn, 0) is NOT immediate 👉 Understand queues = master async JS 🔁 Save this for later 💬 Comment “event loop” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🚀 JavaScript Event Loop Explained (Step-by-Step) JavaScript is single-threaded, meaning it executes one task at a time. So how does it handle asynchronous operations like Promises and setTimeout? Let’s break it down in a simple way: 🔹 Step 1: Synchronous Code (Call Stack) All synchronous code runs first in the Call Stack. Example: console.log("Hello") → executes immediately 🔹 Step 2: Promises (Microtask Queue) When a Promise resolves, its ".then()" callback is added to the Microtask Queue. This queue has higher priority than others. 🔹 Step 3: setTimeout (Callback Queue) setTimeout is handled by Web APIs and, after the timer completes, its callback moves to the Callback Queue. 🔹 Step 4: Event Loop The Event Loop continuously checks: • Is the Call Stack empty? • If yes, execute tasks from queues ⚡ Key Rule: Microtask Queue (Promises) executes before Callback Queue (setTimeout) 💡 Example: console.log("Hello"); Promise.resolve().then(() => console.log("Promise")); setTimeout(() => console.log("Callback"), 0); 📌 Output: Hello Promise Callback Even with 0ms delay, setTimeout runs last because it waits in the Callback Queue. --- 🎯 Why this matters: • Better understanding of async behavior • Easier debugging • Stronger interview preparation 🔖 Save this for future reference #JavaScript #EventLoop #MERN #WebDevelopment #Frontend #NodeJS
To view or add a comment, sign in
-
-
🚀 JavaScript for Angular Developers – Series 🚀 Day 3 – Event Loop & Async Behavior (Why Code Runs Out of Order) Most developers think: 👉 “JavaScript runs line by line” 🔥 Reality Check 👉 JavaScript is: 👉 Single-threaded but asynchronous 🔴 The Problem In real projects: ❌ Code runs in unexpected order ❌ setTimeout behaves strangely ❌ API responses come later ❌ Debugging becomes confusing 👉 Result? ❌ Timing bugs ❌ Race conditions ❌ Hard-to-debug issues 🔹 Example (Classic Confusion) console.log('1'); setTimeout(() => { console.log('2'); }, 0); console.log('3'); 👉 What developers expect: 1 2 3 ✅ Actual Output: 1 3 2 🧠 Why This Happens 👉 Because of Event Loop 🔹 How It Works (Simple) Synchronous code → Call Stack Async tasks → Callback Queue Event Loop → checks stack Executes queued tasks when stack is empty 👉 That’s why setTimeout runs later 🔥 🔹 Angular Real Example TypeScript console.log('Start'); this.http.get('/api/data').subscribe(data => { console.log('Data'); }); console.log('End'); Output: Start End Data 👉 HTTP is async → handled by event loop 🔹 Microtasks vs Macrotasks (🔥 Important) ✔ Promises → Microtasks (higher priority) ✔ setTimeout → Macrotasks 👉 Microtasks run first 🎯 Simple Rule 👉 “Sync first → then async” ⚠️ Common Mistake 👉 “setTimeout(0) runs immediately” 👉 NO ❌ 👉 It runs after current execution 🔥 Gold Line 👉 “Once you understand the Event Loop, async JavaScript stops being magic.” 💬 Have you ever been confused by code running out of order? 🚀 Follow for Day 4 – Debounce vs Throttle (Control API Calls & Improve Performance) #JavaScript #Angular #Async #EventLoop #FrontendDevelopment #UIDevelopment
To view or add a comment, sign in
-
-
Ever wondered what actually happens when you use new in JavaScript? 🤔 Today I learned: 👉 How objects are created behind the scenes 👉 How prototypes are linked 👉 How constructors build instances Documented everything in this article 👇 https://lnkd.in/gr2UykHg #JavaScript #100DaysOfCode #WebDev #chaicode Chai Code Hitesh ChoudharyPiyush Garg Akash Kadlag Suraj Kumar Jha
To view or add a comment, sign in
-
When I started learning JavaScript, async code felt unpredictable. Things didn’t execute in order. Logs appeared out of nowhere. And promises felt like “magic”. The real issue? I didn’t understand callbacks. Everything in async JavaScript builds on top of them. So I wrote this article to break it down clearly: 👉 Execution flow 👉 Sync vs async callbacks 👉 Why they still matter in modern code If async JS has ever felt confusing, this will help. https://lnkd.in/g7DJ7yXX #JavaScript #LearningToCode #Callbacks #SoftwareDevelopment
To view or add a comment, sign in
-
#js #14 **What is Function Hoisting?** 👉 Function hoisting means: JavaScript moves function declarations to the top of their scope during the memory phase 🔹 1. Function Declaration (Fully Hoisted) sayHello(); function sayHello() { console.log("Hello"); } ✅ Output: Hello 🤔 Why does this work? Because internally JavaScript treats it like: function sayHello() { console.log("Hello"); } sayHello(); 👉 The entire function (code + body) is hoisted ✔ You can call it before declaration 🔹 2. Function Expression (NOT fully hoisted) sayHi(); var sayHi = function() { console.log("Hi"); }; ❌ Output: TypeError: sayHi is not a function 🤔 Why? Internally: var sayHi = undefined; // hoisted sayHi(); // ❌ undefined() sayHi = function() { console.log("Hi"); }; 👉 Only the variable is hoisted, not the function 🔹 3. let / const Function Expression sayBye(); let sayBye = function() { console.log("Bye"); }; ❌ Output: ReferenceError 🤔 Why? Because of TDZ (Temporal Dead Zone) sayBye is hoisted But not initialized So you cannot access it before declaration 🧩 How it works internally (Memory Phase) Example: function a() {} var b = function() {}; let c = function() {}; 👉 Memory creation: a → full function stored ✅ b → undefined c → uninitialized (TDZ) 🧑🍳 Simple analogy Think of it like tools 🧰: Function Declaration 👉 Full tool ready before work starts Function Expression 👉 Only box is there, tool comes later let/const 👉 Box is locked (TDZ) until opened 🎯 Important Points Function declarations are fully hoisted Function expressions behave like variables var → undefined let/const → TDZ Only declarations (not assignments) are hoisted 🧾 Final Summary Function declaration → fully hoisted Function expression → partially hoisted let/const → TDZ applies 💡 One-line takeaway 👉Only function declarations are completely hoisted; function expressions follow variable hoisting rules #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development