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
JavaScript Event Loop: Understanding Async Timing
More Relevant Posts
-
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
-
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
-
🚀 Day 11/21 – JavaScript DOM Project Built a Simple Expense Tracker using JavaScript DOM manipulation. 🛠 Features implemented: ✅ Add income and expense transactions ✅ Real-time balance calculation ✅ Transaction history list ✅ Delete transactions ✅ Dynamic UI updates 💡 Key Learning: Learned how to manage application state using arrays and update the DOM dynamically when the data changes. #Day11 #JavaScript #DOM #ExpenseTracker #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
-
JavaScript is single-threaded, but asynchronous behavior is managed by the Event Loop. 👉 Execution Order: 1️⃣ Call Stack – Executes synchronous code 2️⃣ Microtask Queue – Promises (High Priority) 3️⃣ Macrotask Queue – setTimeout, setInterval, DOM events (Low Priority) The Event Loop processes all microtasks before executing the next macrotask. That’s why Promise callbacks run before setTimeout — even with 0ms delay. Understanding this mechanism is crucial for writing efficient and non-blocking JavaScript applications. #JavaScript #EventLoop #AsyncJS #FrontendDeveloper #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
-
JavaScript is single-threaded… yet it handles timers, API calls, and user events at the same time. 🤯 How? Meet the Event Loop 🔁 — the system that keeps JavaScript running smoothly. Here’s the simple flow: 🧠 Call Stack – Executes synchronous code first 🌐 Web APIs – Handles async tasks like setTimeout, fetch, DOM events 📥 Queues – Completed tasks wait here to run But there’s a twist 👇 ⚡Microtask Queue (High Priority) Examples: Promise.then(), queueMicrotask() ⏳ Macrotask Queue (Lower Priority) Examples: setTimeout, setInterval, DOM events When the stack is empty, the Event Loop checks: 1️⃣ Microtasks first 2️⃣ Then Macrotasks Example: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); Output 👇 1 → 4 → 3 → 2 Because Promises run before setTimeout. Understanding this small concept can save you hours of debugging async code.🚀 Yogita Gyanani Piyush Vaswani #JavaScript #WebDevelopment #AsyncProgramming #FrontendDevelopment #EventLoop #CodingConcepts
To view or add a comment, sign in
-
-
🚀 30 Days of JavaScript – Day 10 Today I built a small logical puzzle game called Bulls & Cows. The program generates a secret number and the player must guess it. After each guess, the program gives hints using Bulls (correct digit & position) and Cows (correct digit but wrong position). 🧠 Concepts Used: • loops • string indexing • conditional logic • problem-solving approach 🎥 Demo below 👇 Full source code in the comments. #JavaScript #CodingChallenge #ProblemSolving #WebDevelopment #LearningJavaScript
To view or add a comment, sign in
-
⚠️ The Danger of Splicing Arrays in a Loop "While solving the 'Move Zeroes' challenge today, I encountered a classic JavaScript pitfall: Modifying an array's length while iterating over it. The Mistake: Using .splice() inside a for loop. When you remove an element, the next one shifts left, and your loop index skips it! The Lesson: Always adjust your index or, even better, use the Two-Pointer technique. It's not just safer; it's much more performant for large datasets. Small bugs teach the biggest lessons! 🚀" "Did you know? JavaScript (ES6) allows you to swap array elements in a single line using destructuring : [a, b] = [b, a]. Clean, readable, and efficient!" Feel free to check out my progress and solutions on my LeetCode profile: I've shared my LeetCode profile link in the first comment below! #JavaScript #CodingTips #WebDevelopment #ProblemSolving #LeetCode #AngularDeveloper
To view or add a comment, sign in
-
-
⚡ A Common JavaScript Misconception About the Event Loop Many developers think: "setTimeout(fn, 0) runs immediately." That’s incorrect. Even with 0 milliseconds, the callback still goes through the Event Loop cycle. Example: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B Why? Because JavaScript has two queues: 🔹 Microtask Queue → Promises, MutationObserver 🔹 Callback Queue → setTimeout, setInterval The Event Loop always processes microtasks first. Understanding this difference is critical when debugging async behavior in real applications. Master the Event Loop → Master asynchronous JavaScript. #javascript #asyncjavascript #webdevelopment #frontend #mernstack
To view or add a comment, sign in
-
-
🚨 Most developers get this wrong about the JavaScript Event Loop What do you think this prints? 👇 console.log("Start"); setTimeout(() => console.log("Timeout"), 0); console.log("End"); Many people expect: ❌ Start ❌ Timeout ❌ End But the actual output is: ✅ Start ✅ End ✅ Timeout Why? 🤔 Because JavaScript is single-threaded and uses the Event Loop to handle async tasks. Here’s what really happens behind the scenes: 1️⃣ console.log("Start") → runs immediately in the Call Stack 2️⃣ setTimeout() → moves to Web APIs 3️⃣ console.log("End") → runs next (still synchronous) 4️⃣ Timer finishes → callback goes to Callback Queue 5️⃣ Event Loop pushes it to the Call Stack when it's empty 6️⃣ console.log("Timeout") finally runs 💡 Even setTimeout(..., 0) is never truly instant. If you understand this concept, debugging async JavaScript becomes 10x easier. 💬 Comment “EVENT LOOP” if you want a deeper breakdown with Promises & Microtasks. #javascript #webdevelopment #nodejs #frontend #backend #programming #eventloop #coding
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
Great post. This lays the foundations of JS event loop. Almost broke my head trying to understand it the first time.