⚡ Microtask vs Macrotask Why does Promise.then() run before setTimeout() — even when the delay is 0 ms? Most developers think 0 ms means “immediately”. But JavaScript has a different rule. Here’s what actually happens: 1️⃣ Call Stack executes 2️⃣ All Microtasks run 3️⃣ One Macrotask runs 4️⃣ Repeat And since Promises go to the Microtask Queue, they execute BEFORE Macrotasks like setTimeout(). That’s why: Promise > setTimeout Understanding this small detail can completely change how you debug async code. 💬 Quick Question: What will log first? setTimeout(() => console.log("A"), 0) Promise.resolve().then(() => console.log("B")) Comment your answer 👇 #JavaScript #WebDevelopment #FrontendDeveloper #AsyncProgramming #EventLoop #KeepCoding
JavaScript Async Execution: Promise vs setTimeout
More Relevant Posts
-
JavaScript is single-threaded, but async code doesn’t just run whenever it feels like it. The engine processes: The call stack Then microtasks (Promises) Then macrotasks (setTimeout, etc.) Which means this: console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Logs: Start End Promise Timeout Even with 0ms, setTimeout waits until the microtask queue is empty. Once I understood that, async bugs stopped feeling random. The event loop isn’t just trivia, it’s how you reason about timing instead of guessing. #JavaScript #EventLoop #AsyncProgramming #WebDevelopment
To view or add a comment, sign in
-
🚀 𝗪𝗵𝗼 𝗘𝘅𝗲𝗰𝘂𝘁𝗲𝘀 𝗙𝗶𝗿𝘀𝘁 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? 🚀 I’ve just shared a handy guide—“Who Executes First in JavaScript: Synchronous, Microtasks & Macrotasks”—to help you predict exactly when your code runs and avoid those nagging timing bugs. 𝗠𝗮𝗶𝗻 𝘁𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀: - 𝗦𝘆𝗻𝗰 𝗳𝗶𝗿𝘀𝘁: Plain console.log calls run immediately in sequence. - 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 𝗻𝗲𝘅𝘁: Promises (and await continuations) always beat macrotasks. - 𝗠𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 𝗹𝗮𝘀𝘁: Even setTimeout(..., 0) waits until after all sync and microtasks. Want to see this in action? Check out the slide deck for live code examples—and let me know which timing gotcha has tripped you up the most! #javascript
To view or add a comment, sign in
-
I once spent hours debugging something that made no sense. The code looked correct. The logic was simple. But the console logs were appearing in a strange order. Something like this: Promise 𝗿𝗲𝘀𝗼𝗹𝘃𝗲𝗱 Then 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 Then another log I expected earlier. That’s when I discovered something many JavaScript developers overlook: Not all async tasks are treated the same. Some go to the 𝗺𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗾𝘂𝗲𝘂𝗲. Some go to the 𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸 𝗾𝘂𝗲𝘂𝗲. And JavaScript always clears microtasks first before moving to the next macrotask. That’s why: Promises, 𝗾𝘂𝗲𝘂𝗲𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸, 𝗠𝘂𝘁𝗮𝘁𝗶𝗼𝗻𝗢𝗯𝘀𝗲𝗿𝘃𝗲𝗿 run earlier. While things like: 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁, 𝘀𝗲𝘁𝗜𝗻𝘁𝗲𝗿𝘃𝗮𝗹, 𝗗𝗢𝗠 𝗲𝘃𝗲𝗻𝘁𝘀 wait for the next event loop cycle. Once I understood this, a lot of 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝘀 𝘄𝗲𝗶𝗿𝗱 moments stopped being weird. They were just the event loop doing exactly what it was designed to do. Sometimes the bug isn’t in the code. It’s in our 𝗺𝗲𝗻𝘁𝗮𝗹 𝗺𝗼𝗱𝗲𝗹 of how the runtime works. #JavaScript #EventLoop #FrontendEngineering #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Stop adding 100+ event listeners to your code! Ever built a long list or a dynamic dashboard and felt your code getting "heavy"? 🏋️♂️ If you're manually attaching a click listener to every single item, you're missing out on one of JavaScript’s most powerful patterns: Event Delegation. The Magic of Event Bubbling 🫧 In the DOM, events don't just stay where they happen. When you click a button, that event "bubbles" up like a bubble in water—from the button, to its parent, to the body, all the way to the root. The Solution: Event Delegation 🤝 Instead of giving a listener to every child, you give one listener to their parent. Why this wins: ✅ Memory Efficiency: One listener uses far less memory than 100. ✅ Dynamic Support: It automatically works for new items added later! ✅ Cleaner Code: Centralize your logic in one place. How are you optimizing your DOM interactions lately? Let's discuss below! 👇 #JavaScript #WebDevelopment #CodingTips #FrontendDev #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
💡 Closures in JavaScript — Explained Without Code Imagine a function leaving home wearing a 🎒 Backpack of Memories. Inside that backpack? 👉 Variables from where it was created. Even after the parent function disappears… the child function still remembers. That’s a Closure. 🔐 Why developers love closures: • Protect private data • Avoid global chaos • Enable powerful patterns like counters, modules & state management Quick challenge for you 👇 If a function carries its parent’s variables everywhere… 👉 Would you call that memory, privacy, or magic? 😄 Comment your answer — and tell me: When did Closures finally click for you? #JavaScript #Closures #WebDevelopment #FrontendDevelopment #ProgrammingConcepts #DevCommunity #LearnToCode
To view or add a comment, sign in
-
-
Adding event listeners to every element? There’s a smarter way in JavaScript. It’s called Event Delegation. Instead of attaching multiple event listeners to child elements, you attach one listener to the parent element. Why this works? Because of event bubbling. When an event happens, it moves up the DOM tree: Child → Parent → Document Example: document.getElementById("list").addEventListener("click", (e) => { if (e.target.tagName === "LI") { console.log("List item clicked"); } }); Now a single listener can handle all child element clicks. Benefits: • Better performance • Cleaner code • Works for dynamically added elements Small concepts like this make a big difference in real projects. Follow for more JavaScript concepts explained visually. #javascript #frontenddeveloper #webdevelopment #coding #softwareengineering
To view or add a comment, sign in
-
-
Day 13/30: Uploading More Than Just Images 🖼️⚡ One step closer to the halfway point! For Day 13 of my #30DaysOfCode challenge, I built a functional Image Uploader using Vanilla JavaScript. While it looks simple, this project was a great exercise in: File Handling: Reading user-selected files directly from the browser. Object URLs: Using URL.createObjectURL() to generate instant local previews. Event Management: Registering listeners correctly to avoid duplicate stacking. State Reset: Clearing input.value so the same file can be re-uploaded. It's projects like these that remind you how much power the browser already has — no libraries needed! Live Demo: https://lnkd.in/d5QH9guT Onwards to Day 14! #30DaysOfCode #JavaScript #WebDevelopment #FrontendDev #BuildInPublic #100DaysOfCode #VanillaJS
To view or add a comment, sign in
-
JavaScript Event Loop — Microtask vs Macrotask setTimeout(() => console.log("Timeout"), 0) Promise.resolve().then(() => console.log("Promise")) Output: Promise Timeout Why? Because: • Promise callbacks go to the Microtask queue • setTimeout goes to the Macrotask queue • Microtasks run before Macrotasks Understanding the event loop helps avoid async confusion and race conditions. If you know this, debugging async becomes much easier. #JavaScript #EventLoop #AsyncProgramming #Frontend
To view or add a comment, sign in
-
If you understand this, you understand async JavaScript. There are TWO important queues: 1️⃣ Microtask Queue 2️⃣ Macrotask Queue Example: console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output: Start End Promise Timeout Why? Execution order: Run synchronous code Empty Microtask queue Take one Macrotask Repeat Microtasks include: • Promise callbacks • queueMicrotask Macrotasks include: • setTimeout • setInterval • I/O Promise always runs before setTimeout. This is critical when debugging race conditions. #javascript #eventloop #webdevelopment #frontend
To view or add a comment, sign in
-
Proto Toolkit Built something small but useful ☑️ A lightweight JavaScript prototype utility library that adds extra helper methods to native objects. Currently includes: • mask() – Easily mask sensitive strings (like phone numbers, IDs, etc.) • toAbbreviatedName() – Convert full names into abbreviated format Install: npm i proto-toolkit NPM: https://lnkd.in/gSskZZ68 Documentation: https://lnkd.in/g8NvNV2v Simple. Minimal. Zero dependencies. Would genuinely appreciate feedback from the community #BuildInPublic #LearnInPublic
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
B