🌱 Back to Learning JavaScript (Deep Dive Edition) JavaScript’s async behavior isn’t just about the Event Loop it’s powered by two hidden players: Microtasks and Macrotasks. Here’s what I learned after diving deeper. 👉 Microtasks vs Macrotasks We all know the Event Loop keeps JavaScript non-blocking… But what many developers don’t realize is that there are actually two separate queues managing async tasks. 🔹 Microtask Queue Handles: Promise.then(), async/await, queueMicrotask(), MutationObserver Executes immediately after the current synchronous code — before rendering or macrotasks. 🔹 Macrotask Queue (Task Queue) Handles: setTimeout, setInterval, setImmediate, I/O, and fetch callbacks Runs after all microtasks are cleared. Example: console.log("Start"); setTimeout(() => console.log("Macrotask (Timeout)"), 0); Promise.resolve().then(() => console.log("Microtask (Promise)")); console.log("End"); Output: Start End Microtask (Promise) Macrotask (Timeout) 🔎 Something most people don’t know: If microtasks keep queuing themselves (like nested Promises), the browser can’t render causing what’s known as microtask starvation. ✨ Bonus Tip: Rendering happens between macrotasks, not microtasks. That’s why blocking the microtask queue can make your UI feel frozen. 🔑 Takeaway: Knowing how JavaScript schedules microtasks vs macrotasks gives you real control over async behavior, performance, and rendering smoothness. #JavaScript #AsyncProgramming #WebDevelopment #Frontend #EventLoop #JavaScriptInternals #Promises #CodingJourney #LearnInPublic #100DaysOfCode
"Understanding JavaScript's Microtasks and Macrotasks"
More Relevant Posts
-
🚀 My “Aha!” JavaScript Moment: Why does var print 3 three times? A few days ago, I was revisiting some JavaScript fundamentals… and I came across this classic piece of code 👇 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } I expected: 0 1 2 But guess what I got? 3 3 3 😅 I paused for a second and thought — “Wait… what just happened?” 🧠 The Moment of Clarity Here’s what’s really going on: var in JavaScript is function-scoped, not block-scoped. So inside that for loop, all iterations share one single i variable. By the time the setTimeout callbacks actually run (after 1 second), the loop has already finished — and i has become 3. So all three callbacks look at the same i, and print 3. Boom 💥 — mystery solved. ✅ The Fix? Use let When we switch to let, something magical happens: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Now, let is block-scoped, meaning each iteration gets its own copy of i. Each callback “remembers” the value from that iteration. Result: 0 1 2 💡 My Mental Model I now think of it like this: Using var: one whiteboard where you keep erasing and writing new numbers. Everyone who looks later sees the same final number. Using let: each student gets their own notepad — they all remember their own number. 🧩 Key Takeaway Keyword Scope Loop Behavior Output var Function-scoped Shared variable 3, 3, 3 let Block-scoped New variable each iteration 0, 1, 2 We often jump into frameworks, async/await, and APIs… but sometimes it’s these small, fundamental details that sharpen our understanding the most. 🔍 Have you ever had an “aha!” moment like this in JavaScript (or another language)? Share it below — I’d love to hear your story 👇 #JavaScript #WebDevelopment #AsyncJS #Frontend #FullStackDeveloper #LearningToCode #CodingJourney #Developers #CareerGrowth
To view or add a comment, sign in
-
☕ Revisiting JavaScript Event Flow — Capturing, Target & Bubbling Phases Today, I was revising one of the most important concepts in JavaScript — Events and Event Listeners. 💡 It’s fascinating how a single click can travel through multiple layers of the DOM before reaching its destination! Here’s what I learned and revised 👇 🔹 Event & Event Listener JavaScript allows us to respond to user interactions like clicks, key presses, and mouse movements. For example 👇 element.addEventListener("click", () => { console.log("Element clicked!"); }); This method lets us attach multiple handlers to the same element without overwriting existing ones. 🔹 Click Event The click event is one of the most commonly used — and it’s the one I focused on today while understanding how event flow actually works. 🔹 Event Flow in JavaScript Every event in the DOM passes through three phases: 1️⃣ Capturing Phase – The event travels from the top (document) down to the target element. 2️⃣ Target Phase – The exact element that triggered the event receives it. 3️⃣ Bubbling Phase – The event then bubbles back up toward the document. 📘 Example // Capturing phase parent.addEventListener("click", () => { console.log("Parent clicked - Capturing Phase"); }, true); // true → capturing // Bubbling phase (default) child.addEventListener("click", () => { console.log("Child clicked - Bubbling Phase"); }); 👉 When you pass true as the third argument in addEventListener, it listens during the capturing phase. 👉 By default, it’s false, meaning the listener works in the bubbling phase. 🧠 Visual Flow 📤 Document → HTML → Body → Parent → Child → (then bubbles back up 🔁) Understanding this complete flow helped me clearly visualize how events travel and how to control them precisely using capturing and bubbling. 🚀 A huge thanks to CoderArmy, Rohit Negi, and Aditya Tandon Sir 🙏 Your clear explanations and practical examples made this topic so easy to grasp. #JavaScript #EventListener #EventFlow #FrontendDevelopment #WebDevelopment #LearningJourney #Coding #Developer #RohitNegi #AdityaTandon #CoderArmy
To view or add a comment, sign in
-
💡 Day 8/50 – Mastering JavaScript’s Subtle Behaviors 🚀 In JavaScript, sometimes the hardest bugs aren’t syntax errors — they’re “Wait… why did that happen?” moments 😅 Today’s Day 8 questions were built around 3 such moments that every developer faces: --- 🧬 1️⃣ Prototype Inheritance — The Hidden Chain When you create an object using Object.create(), it doesn’t copy properties from the parent… it links to it. That means if a property isn’t found in the child, JavaScript looks up the prototype chain to find it. 👉 This “lookup behavior” often confuses devs who expect a fresh, independent copy. So the next time you’re debugging unexpected data access, remember — It might not be your object, it might be its prototype! --- 🧠 2️⃣ The Mystery of Double .bind() You might think rebinding a function twice changes its context again. But nope! Once you bind a function in JavaScript, it’s permanently bound. Calling .bind() again has no effect — the context (the value of this) stays fixed to the first bind. 💡 Why? Because bind() returns a new function with the this value locked in forever. --- 🧩 3️⃣ Type Coercion + Function Conversion Ever tried adding a function to a string like add + "text"? JavaScript doesn’t crash — it converts your function to a string using its internal toString() method! The result isn’t math; it’s a combination of type coercion and string representation. This is one of those delightful quirks that makes JS both fun and… slightly unhinged 😄 --- 📽️ Watch Day 8 Reel: https://lnkd.in/gBHYWgyi Because once you understand the why, no interviewer can trick you again 😉 #JavaScript #FrontendDevelopment #WebDevelopment #JSInterviewQuestions #CodingChallenge #TechLearning #SoftwareEngineering #Techsharingan #Developers
To view or add a comment, sign in
-
🚀 #Day 3 Understanding JavaScript Event Loop & React useEffect Timing Today, I took a deep dive into one of the most powerful — yet often confusing — topics in JavaScript: the Event Loop 🔁 At first, it looked complex. But once I started writing small examples and observing outputs step-by-step, everything became crystal clear 💡 🔍 What I learned: 🧠 The Event Loop JavaScript is a single-threaded language — meaning it can execute only one task at a time. But thanks to the Event Loop, it can still handle asynchronous operations (like setTimeout, fetch, or Promise) efficiently without blocking the main thread. Here’s how it works 👇 1️⃣ Call Stack — Executes synchronous code line by line. 2️⃣ Web APIs — Handles async tasks (like timers, fetch). 3️⃣ Microtask Queue — Holds resolved Promises and async callbacks. 4️⃣ Callback Queue — Stores setTimeout, setInterval callbacks. The Event Loop continuously checks: “Is the call stack empty? If yes, then push the next task from the microtask queue — and then from the callback queue.” That’s how JavaScript manages async code without breaking the flow ⚡ ⚛️ In React: useEffect() runs after the component renders, and async tasks inside it still follow the Event Loop rules. That’s why: console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output: Start → End → Promise → Timeout ✅ 💬 Takeaway: Once you understand the Event Loop, async code and React effects start making perfect sense! #JavaScript #ReactJS #FrontendDevelopment #EventLoop #AsyncProgramming #WebDevelopment #ReactHooks #LearningInPublic #DevelopersJourney #CodeBetter
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop Have you ever wondered how JavaScript — a single-threaded language — handles async tasks like setTimeout(), fetch(), or Promises without freezing the browser? 🤔 That’s where the Event Loop comes in! 🌀 ⚙️ How it works 1️⃣ Call Stack → Executes synchronous code (like console.log()). 2️⃣ Web APIs → Handle async tasks (like timers or network requests). 3️⃣ Callback Queues Microtask Queue → Handles Promises and async/await. Macrotask Queue → Handles setTimeout, setInterval, etc. 4️⃣ Event Loop → Continuously checks: > “Is the call stack empty?” If yes → It pushes queued callbacks back to the stack for execution. 🧠 Example: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B Because ➡️ A & D → run first (synchronous). C → from Promise (microtask). B → from setTimeout (macrotask). 💡 Takeaway > Event Loop makes JavaScript feel asynchronous — even though it runs on a single thread! ⚡ 🔖 #JavaScript #EventLoop #WebDevelopment #AsyncJS #Frontend #Angular #React #CodingTips
To view or add a comment, sign in
-
JS Learners & Web Devs! Ever wondered why you can call a function before it’s defined in JavaScript, but let or const throw a ReferenceError? Our latest blog dives deep into Hoisting in JavaScript: How JS engine really works Understanding the Temporal Dead Zone (TDZ) Function vs variable hoisting Common pitfalls & best practices Stop guessing and start writing safer, cleaner JS code! https://lnkd.in/dCeqNnRf #javascript #webdevelopment #hoistinginjs #learnjavascript #coding #programming #FrontendDevelopment #webdev #CodeNewbie #wenowadays
To view or add a comment, sign in
-
Understanding Microtasks & Macrotasks in JavaScript — The Event Loop Secret! Ever wondered how JavaScript handles async operations like Promises, timeouts, or fetch calls? 🤔 It’s all managed by the Event Loop, which uses two main types of queues — Microtasks and Macrotasks. 💡 Definition: Microtasks: Tasks that run immediately after the current script, before any rendering. 👉 Includes Promises, MutationObservers, and queueMicrotask(). Macrotasks: Tasks that run after the current event loop cycle, often with a small delay. 👉 Includes setTimeout, setInterval, setImmediate, and I/O tasks. 🧩 Example: console.log("1️⃣ Script start"); setTimeout(() => console.log("4️⃣ setTimeout (Macrotask)"), 0); Promise.resolve().then(() => console.log("3️⃣ Promise (Microtask)")); console.log("2️⃣ Script end"); ✅ Output: 1️⃣ Script start 2️⃣ Script end 3️⃣ Promise (Microtask) 4️⃣ setTimeout (Macrotask) Notice how Promise (Microtask) runs before setTimeout — that’s how the event loop prioritizes microtasks 🚀 ⚙️ Why It’s Important: ✅ Helps you understand async behavior ✅ Prevents performance issues ✅ Explains why Promises run before timers 🔖 #JavaScript #EventLoop #Microtasks #Macrotasks #AsyncProgramming #WebDevelopment #Frontend #JSConcepts #CodingTips #100DaysOfCode #KishoreLearnsJS #DeveloperJourney #WebDevCommunity
To view or add a comment, sign in
-
🚀 JavaScript Event Loop — The Real “Hero” Working Behind the Scenes! Ever wondered how JavaScript, being single-threaded, still manages to handle async tasks, timers, API calls, and UI updates so smoothly? Meet the Event Loop — the silent superstar. Just like in Indian movies, where the main hero fights villains one by one but still wins against the whole gang… JavaScript also handles tasks one at a time and still looks super fast! 😄 --- 🎭 How the Event Loop Works (Movie Analogy Edition) 🎬 Call Stack → The hero fighting enemies face to face (line by line). If the stack is busy, nothing else runs. 🎬 Web APIs / Browser APIs → Side characters handling long tasks (API calls, timeouts, DOM events). 🎬 Callback Queue / Task Queue → Villains waiting outside for their turn (setTimeout, click events, etc). 🎬 Microtask Queue → VIP villains with special entry pass (Promises, Mutation Observers). 🎬 Event Loop → The bouncer checking: "Is the hero free? If yes, send the next villain!" This is how async tasks get processed. --- ⚡ Priority Rule (Important!) Microtasks (Promises) run before normal callbacks. 👉 “Promise mikto ho toh pehle chalega!” (Just like when the VIP enters first 😄) --- 🧠 Why It Matters? Helps you debug async issues Prevents accidental blocking Makes you a better JavaScript developer When you understand the Event Loop, you understand why your code behaves the way it does. --- 🎤 Final Punchline In JavaScript: “Hero ek hi hai — Event Loop. Kaam chahe hazaar ho, handle sab wohi karta hai!” #new #post #react #js #javascript #eventloop #eventloopinjs #javascriptlearn
To view or add a comment, sign in
-
-
Understanding the Event Loop in JavaScript In the world of JavaScript, the Event Loop is a crucial mechanism that enables asynchronous operations to run in a non-blocking way. Since JavaScript is single-threaded, it can only execute one task at a time. This means that without the event loop, operations like network requests or timers would block the main thread and make web applications unresponsive. The Event Loop continuously monitors the call stack and task queues (microtask and macrotask), ensuring that JavaScript can perform asynchronous operations like setTimeout(), fetch(), and Promises efficiently. Here’s a breakdown of the main components: Call Stack: Executes functions in order, one at a time. Web APIs: Handle async tasks like timers, fetch, and DOM events. Microtask Queue: Contains high-priority tasks such as Promises. Macrotask Queue: Handles lower-priority tasks like setTimeout, setInterval, and UI events. The event loop moves tasks from these queues to the call stack only when it’s empty, ensuring smooth, non-blocking execution. Understanding the event loop is essential for writing efficient, responsive, and scalable web applications — especially when dealing with asynchronous behavior, callbacks, and promises. #JavaScript #WebDevelopment #Frontend #Coding #AsyncProgramming #EventLoop #Developers #WebApps #SoftwareDevelopment #ProgrammingConcepts
To view or add a comment, sign in
-
Today I Learned: Iterators & Generators in JavaScript One of the most interesting parts of modern JavaScript is how it handles iteration, and today I finally understood how Iterators and Generators work under the hood! 🧠 1. Iterators An iterator is simply an object that defines how to step through a sequence, one value at a time. It follows the pattern: const iterator = [10, 20, 30][Symbol.iterator](); console.log(iterator.next()); // { value: 10, done: false } console.log(iterator.next()); // { value: 20, done: false } Each call to .next() gives you the next value until done: true. ⚙️ Generators A generator function (defined with function*) automatically creates an iterator for you. function* greet() { yield "Hi"; yield "Hello"; yield "Hey"; } const it = greet(); console.log(it.next().value); // Hi console.log(it.next().value); // Hello What’s cool is that you can pause and resume function execution! 🔥 💡 Key Takeaway: Iterators let you take control of how data is accessed. Generators make it easier to build your own iterators — letting you write asynchronous, lazy, and powerful code structures. Every day, I’m realising how deep JavaScript really is — and how beautiful its design becomes when you understand what’s happening under the hood. #JavaScript #WebDevelopment #LearningInPublic #BackendDevelopment #ES6
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