𝗵𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝘀 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲? It's single-threaded. So how does it handle setTimeout, API calls, and user clicks without freezing? 𝗧𝗵𝗲 𝗮𝗻𝘀𝘄𝗲𝗿: Event Loop Here's what actually happens: JavaScript has 4 main parts: ↳ Call Stack — runs your code ↳ Web APIs — handles async tasks (setTimeout, fetch, DOM events) ↳ Callback Queue — stores completed callbacks ↳ Event Loop — moves callbacks to stack when stack is empty Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); Output: Start End Timeout Wait, why does Timeout come last? ↳ console.log("Start") → runs immediately ↳ setTimeout → sent to Web API ↳ console.log("End") → runs immediately ↳ Stack empty → Event Loop pushes callback ↳ console.log("Timeout") → runs now Even with 0ms delay, setTimeout waits for stack to clear. My takeaway: JavaScript isn't slow. It's just smarter than I thought. Understanding Event Loop = understanding async JavaScript. #JavaScript #FrontendDevelopment #LearningInPublic #SDE
JavaScript Event Loop Explained
More Relevant Posts
-
🚀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗮𝘀𝘆𝗻𝗰/𝗮𝘄𝗮𝗶𝘁: 𝘄𝗵𝘆 𝗶𝘁 𝗹𝗼𝗼𝗸𝘀 𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗯𝘂𝘁 𝗶𝘀𝗻’𝘁 JavaScript doesn’t execute async/await synchronously; it only makes asynchronous code easier to read. Example: console.log("A"); async function test() { console.log("B"); await Promise.resolve("C"); console.log("D"); } test(); console.log("E"); Output: A B E D What actually happens: 1) Global execution starts "A" is printed 2) test() is called "B" is printed 3) await Promise.resolve("C") • The promise is already resolved, but await still pauses, 𝗮𝘄𝗮𝗶𝘁 𝗻𝗲𝘃𝗲𝗿 𝗰𝗼𝗻𝘁𝗶𝗻𝘂𝗲𝘀 𝗶𝗺𝗺𝗲𝗱𝗶𝗮𝘁𝗲𝗹𝘆 • Suspends test execution and lets the rest of the code run first • The remaining code (console.log("D")) is scheduled as a microtask 4) Global code continues "E" is printed 5) Microtask queue runs async function resumes from where it paused "D" is printed See? Nothing got blocked. That’s JavaScript for you, and async/await just keeps async code readable. Thanks to Akshay Saini 🚀 for explaining this concept in Namaste Javascript, which made async/await click for me! 👏👏 #JavaScript #AsyncAwait #EventLoop #FrontendDevelopment #WebDevelopment
To view or add a comment, sign in
-
🔄 JavaScript is single-threaded. So how does it handle multiple tasks at once? Meet the Event Loop. It's the unsung hero that keeps your browser from freezing while waiting for an API call. Many developers use setTimeout or fetch daily without knowing what happens under the hood. Here is the architecture that makes non-blocking I/O possible: 1️⃣ Call Stack (The Boss): JavaScript does one thing at a time. It executes functions LIFO (Last In, First Out). If the stack is busy, nothing else happens. 2️⃣ Web APIs (The Assistants): When you call setTimeout or fetch, the browser takes that task out of the Call Stack and handles it in the background (Web APIs). This frees up the stack to keep running your code! 3️⃣ Callback Queue (The Waiting Room): Once the background task is done (e.g., the timer finishes), the callback function is moved to the Queue. It waits there patiently. 4️⃣ The Event Loop (The Traffic Controller): This is the infinite loop. It constantly checks: - "Is the Call Stack empty?" - "Is there something in the Queue?" - If Stack is Empty AND Queue has items 👉 Move item to Stack. Understanding this flow is the key to debugging weird async behavior. Did you know setTimeout(fn, 0) is a hack to defer execution until the stack is clear? #JavaScript #WebDevelopment #EventLoop #CodingInterview #Frontend #SoftwareEngineering
To view or add a comment, sign in
-
-
JavaScript can be pretty confusing. It's pass-by-value, but what does that even mean? So, let's dive in. In a nutshell: everything in JavaScript is passed by value - it's that simple. But, the type of data you're working with changes everything. Primitives, like numbers or strings, are passed by value - no surprises there. Objects, on the other hand, are passed by value too, but the value is a reference to the object, which is where things get tricky. When you pass a primitive, JavaScript makes a copy of the data, and the original and the copy are independent - easy peasy. But with objects, it's like sharing a secret: if you change the object, everyone who has a reference to it sees the change. You can use the spread operator or structuredClone() to create copies of objects, but be careful - objects and arrays can share references, which can lead to some weird behavior. It's like trying to have a conversation in a crowded room: you think you're talking to one person, but really, everyone is listening. So, to write clean code, use immutability - never change the original data, just return a new version. It's like taking a snapshot: you capture the moment, and then you can move on. And, yeah, it's worth repeating: JavaScript is always pass-by-value. Primitives are safe from external changes, but objects and arrays share references, so be careful. Use the spread operator or structuredClone() to create copies, and always, always embrace immutability for predictable code. Check out this article for more info: https://lnkd.in/g-Nj9Rh6 #JavaScript #Immutability #CleanCode #PassByValue #ProgrammingBestPractices
To view or add a comment, sign in
-
🧠 Microtasks vs Macrotasks in JavaScript If you’ve ever wondered why Promise.then() runs before setTimeout(), this is the reason 👇 🔹 What are Macrotasks? Macrotasks are large tasks scheduled to run later. Examples: setTimeout setInterval setImmediate (Node.js) DOM events I/O operations setTimeout(() => { console.log("Macrotask"); }, 0); 🔹 What are Microtasks? Microtasks are high-priority tasks that run immediately after the current execution, before any macrotask. Examples: Promise.then / catch / finally queueMicrotask MutationObserver Promise.resolve().then(() => { console.log("Microtask"); }); 🔹 Execution Order (Very Important 🔥) console.log("Start"); setTimeout(() => console.log("Macrotask"), 0); Promise.resolve().then(() => console.log("Microtask")); console.log("End"); Output: Start End Microtask Macrotask 🔹 Why This Happens? JavaScript follows this rule: 1️⃣ Execute synchronous code 2️⃣ Run all microtasks 3️⃣ Run one macrotask 4️⃣ Repeat 👉 Microtask queue is always drained first 🔹 Common Interview Gotcha 😅 setTimeout(() => console.log("timeout"), 0); Promise.resolve() .then(() => console.log("promise 1")) .then(() => console.log("promise 2")); Output: promise 1 promise 2 timeout 💡 Takeaway Microtasks = urgent callbacks Macrotasks = scheduled callbacks Understanding this helps you: ✅ Debug async bugs ✅ Avoid UI freezes ✅ Write predictable async code If this cleared up the event loop for you, drop a 👍 #JavaScript #EventLoop #AsyncJS #FrontendDevelopment
To view or add a comment, sign in
-
🟨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗮𝘆 𝟰𝟴: 𝗔𝘀𝘆𝗻𝗰 & 𝗔𝘄𝗮𝗶𝘁 (𝗗𝗲𝗲𝗽 𝗯𝘂𝘁 𝗦𝗶𝗺𝗽𝗹𝗲) Some JavaScript operations take time — and async & await help us handle them cleanly. 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮𝘀𝘆𝗻𝗰? • async is a keyword used to create an async function • An async function always returns a Promise • Even a normal return value is wrapped inside a Promise async function getData() { return "JavaScript"; } 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮𝘄𝗮𝗶𝘁? • await can only be used inside an async function • It pauses the execution of that function only • JavaScript continues running other code const result = await fetch("/api"); 🔹 𝗛𝗼𝘄 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗪𝗼𝗿𝗸𝘀 • Code runs normally until it hits await • Function execution is suspended • Once the Promise resolves, execution continues from the same line 🔹 𝗪𝗵𝘆 𝗪𝗲 𝗨𝘀𝗲 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 • Makes async code look synchronous • Improves readability • Easier error handling with try / catch 🔹 𝗞𝗲𝘆 𝗣𝗼𝗶𝗻𝘁 Async & await do not block JavaScript They only pause the async function — not the event loop. 💬 GitHub link in the comments for examples #JavaScript #Day48 #100DaysOfCode #Frontend
To view or add a comment, sign in
-
🧵 How JavaScript Does 10 Things at Once (While Being Single-Threaded) 🔄 Ever wondered how JavaScript handles API calls, timers, or async tasks without freezing the browser UI? The secret is the Event Loop. Even though JavaScript is single-threaded (it can do only one thing at a time), the Event Loop allows it to be asynchronous and non-blocking. Here’s a simple 4-step breakdown of how it works 👇 1️⃣ Call Stack This is the “Now” zone. JavaScript executes synchronous code here. If a function is in the stack, the engine is busy. 2️⃣ Web APIs / Node APIs When you use `setTimeout`, `fetch`, or DOM events, JavaScript hands them off to the browser/Node environment. This keeps the call stack free so the UI doesn’t freeze. 3️⃣ Callback Queue & Microtask Queue Once async tasks complete, their callbacks wait here. 👉 Promises (Microtasks) always run before timers (`setTimeout`). 4️⃣ Event Loop This is the coordinator. It constantly checks: • Is the Call Stack empty? • If yes → move the next task from the queue to the stack. 🔑 Golden Rule: Avoid blocking the Event Loop with heavy synchronous code — otherwise users will experience laggy interfaces. Learning this really helped me understand async JavaScript better 🚀 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #EventLoop #Programming #javascript
To view or add a comment, sign in
-
-
⚡ JavaScript Event Loop — The Concept That Makes JS Feel “Fast.” Ever wondered how JavaScript handles multiple tasks even though it’s single-threaded? Here are the key things to understand: 🧩 Call Stack Runs your code line by line (one task at a time). 🌐 Web APIs (Browser) Handles slow tasks like setTimeout, fetch, DOM events, etc. 📥 Callback Queue (Task Queue) Stores callbacks waiting to run after the stack is empty. ⚡ Job Queue (Microtask Queue) Promises go here — and it runs before the callback queue ✅ 🔁 Event Loop Continuously checks if the call stack is empty, then pushes queued tasks back to execution. Understanding this helps you: ✅ predict async output order ✅ fix “why is this logging first?” confusion ✅ write better Promise/async-await code ✅ understand sequence vs parallel vs race I wrote a beginner-friendly breakdown with examples. Link in the comments 👇 #JavaScript #WebDevelopment #Frontend #Programming #LearnJavaScript #SoftwareEngineering #Async #EventLoop
To view or add a comment, sign in
-
-
JavaScript – Execution Context Before JavaScript runs even a single line of your code, it prepares a working space for it. That space is called an Execution Context. In simple words: Execution Context is where JavaScript remembers things and runs your code Whenever JavaScript runs: ● Your whole program → one big Execution Context ● Every function call → a new small Execution Context Each one is created in two steps: 1️⃣ Memory Phase ● Variables are created → undefined ● Functions are stored fully 2️⃣ Execution Phase ● Code runs line by line ● Variables get real values ● Functions are executed Example: *** var a = 5; function show() { var b = 3; console.log(a + b); } show(); *** How JavaScript works: ● Creates a global context ◦ a → undefined ◦ show → saved ● Runs code ◦ a = 5 ◦ show() is called → new context is created ● Inside show() ◦ b = 3 ◦ Prints 8 JavaScript manages these contexts using a Call Stack: ● Global goes first ● Each function goes on top ● When a function finishes, it is removed This is why understanding Execution Context helps you: ● Understand hoisting ● Read call stack errors ● Master scope & closures ● Debug with confidence This is how JavaScript thinks before it acts. #Day1 #JavaScript #Frontend #WebDevelopment #LearningInPublic #React #Developers #CareerGrowth
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