setTimeout(fn, 0) looks simple. Until a Promise shows up… and breaks your expectations. You write this: setTimeout(() => console.log("timeout"), 0); Promise.resolve().then(() => console.log("promise")); And you think: “Timeout has 0 delay… it should run first.” But the output is: ->promise ->timeout So what’s actually happening? Not magic. Not randomness. Just how JavaScript is designed. When your code runs, this is the order: Run all synchronous code Execute all Promises (microtasks) Then execute setTimeout (macrotasks) Now read that again. 👉 Promises are not faster 👉 They are just scheduled differently Here’s the hidden detail most devs miss: Even if your setTimeout is ready… JavaScript will pause it until every single Promise is finished. So in reality: setTimeout(fn, 0) → “Run me later” Promise.then() → “Run me right after this code” That’s why Promises always win. Not because they’re special… But because the event loop always clears microtasks first. The simple mental model: 👉 sync → promises → timers Once you understand this, you stop guessing async behavior… …and start predicting it. #javascript #webdev #eventloop #programming #promises #settimeout #nodejs #javascript #nestjs #backend #softwareengineering
Bhushan Mayekar’s Post
More Relevant Posts
-
💻 5 React mistakes I stopped making (and it improved my code a lot) When I started with React, I used to write code that worked… But not code that was clean, scalable, and maintainable. Here are 5 mistakes I fixed: ❌ 1. Writing everything in one component 👉 Now I break UI into small reusable components ❌ 2. Ignoring proper state management 👉 Learned when to use useState vs useEffect vs lifting state ❌ 3. Not handling performance 👉 Started using memoization (useMemo, useCallback) ❌ 4. Poor folder structure 👉 Now I follow a clean project structure ❌ 5. Debugging randomly 👉 Now I debug step-by-step with proper logs Small changes… but huge difference in code quality 🚀 Still learning every day 👨💻 Which mistake did you make the most? 😅 #ReactJS #FrontendDevelopment #JavaScript #CleanCode #WebDevelopment #SoftwareEngineer
To view or add a comment, sign in
-
Real talk — useEffect almost broke my brain today. 😅 My React journey continues, and I came across one of the trickiest hooks so far. useEffect. At first I felt completely lost. The Codecademy lesson talked about cleanup functions, dependency arrays, side effects — and honestly? My head was spinning. But after stepping back and breaking it down in simpler terms, here's what finally made sense to me: useEffect lets you run code at SPECIFIC MOMENTS in your component's life. Three moments to remember: ```jsx // 1. Run AFTER EVERY render useEffect(() => { }); // 2. Run ONLY ONCE when the page loads useEffect(() => { }, []); // 3. Run WHEN a specific value changes useEffect(() => { }, [forecastType]); ``` The array at the end is called the dependency array — and it controls WHEN the code runs. The analogy that helped me? Think of it like a home security camera 📹 - No array — records 24/7 - Empty array — only records on day one - With a value — only records when that thing changes It's still not 100% clear to me yet — and that's okay. Some concepts take time to really click. 🙏 The lesson today wasn't just about useEffect though — it was about being honest with myself when something is hard, taking a break, and coming back to it instead of forcing it. Still learning, still building, still showing up every day. 💪 Is there a React concept that confused you when you first learned it? Drop it below 👇 #React #JavaScript #useEffect #Frontend #LearningInPublic #100DaysOfCode #SelfTaught
To view or add a comment, sign in
-
Stop guessing. Start understanding. 🚀 Ever been confused about why End! prints before your Promises resolve? Or why setTimeout(0) isn't really zero seconds? The JavaScript Event Loop isn't a mystery; it's a powerful priority system. This diagram breaks it down step-by-step. The key secret to execution order is that Promises always have priority over timers! Here’s the TL;DR: 1️⃣ Sync Code (Start/End) runs first. 2️⃣ Promise Handlers (Microtasks) are high-priority and run immediately after sync code. 3️⃣ Timer callbacks (setTimeout) are Macrotasks and run after ALL microtasks. Mastering this is the single best way to write efficient, non-blocking code. Save this infographic for a reference when debugging! 📌 Tag a fellow developer who needs to see this. 👇 #JavaScript #WebDev #TechExplained #EventLoop #CodingLife #SoftwareEngineer #FrontEnd #FullStack #ProgammingTips #LearnToCode #AsynchronousJS
To view or add a comment, sign in
-
-
Most React tutorials show basic folder structures—but real-world projects need something more scalable. Here’s the approach I follow to keep my projects clean and production-ready: 🔹 I separate logic by features, not just files 🔹 Keep components reusable and independent 🔹 Move all API logic into services (no messy calls inside components) 🔹 Use custom hooks to simplify complex logic 🔹 Maintain global state with Context or Redux only when needed 🔹 Keep utilities and helpers isolated for better reuse 💡 The goal is simple: Write code today that’s easy to scale tomorrow. As projects grow, structure becomes more important than syntax. What’s your approach—feature-based or file-based structure? 👇 Follow me - Abhishek Anand 😍 #share #like #repost #ReactJS #FrontendDevelopment #MERNStack #CleanCode #WebDevelopment #Javascript Credit #jamesCodeLab
To view or add a comment, sign in
-
-
React journey continues — and today's lesson was all about Components. 🧱 A few days ago I talked about JSX. Then the DOM and Virtual DOM. Today? Components made my brain light up in the best way. Here's what I learned: A component is just a JavaScript function that returns JSX. That's it. ```jsx function AnimalFacts() { return <p>Fun fact about animals!</p>; } ``` But what surprised me the most? You can use it like an HTML tag: ```jsx <AnimalFacts /> ``` That one line renders your entire component. Mind = blown. 🤯 The analogy that made it all click for me? LEGO bricks 🧱 Each component is its own brick — built separately, snapped together to make something bigger. And the best part? They're REUSABLE. One component can work for a dolphin, a lobster, and a starfish! Self taught, learning in public, and taking it one concept at a time. 💪 If you're on a similar journey, let's connect! And if you're experienced — what's YOUR favourite analogy for explaining components? Drop it below 👇 #React #JavaScript #Frontend #Components #LearningInPublic #100DaysOfCode #SelfTaught
To view or add a comment, sign in
-
-
😵💫 “Why is my setTimeout running AFTER my Promise?” This question confused me for a long time while working with JavaScript. I thought: 👉 setTimeout(0) = runs immediately 👉 Promise = async → should run later But I was WRONG. I tested this 👇 console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); 👉 Output shocked me: Start → End → Promise → Timeout Then I saw this diagram 👇 …and everything clicked. 💡 The truth: JavaScript doesn’t just run “async code” randomly. It follows a strict priority system: ⚡ Microtasks (Promises) → HIGH priority ⏳ Macrotasks (setTimeout) → LOW priority 🔄 What actually happens: Run all sync code → Start, End Clear Microtask Queue → Promise Then Macrotask Queue → Timeout 🔥 The moment I understood this: Debugging async code became 10x easier No more guessing execution order My React apps felt more predictable 📌 One line to remember: 👉 “Promises beat setTimeout. Always.” If you’re learning frontend, this is one concept you can’t ignore. What was your “wait… what?!” moment in JavaScript? 👇 #JavaScript #FrontendDevelopment #Coding #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
-
Most React tutorials show basic folder structures—but real-world projects need something more scalable. Here’s the approach I follow to keep my projects clean and production-ready: 🔹 I separate logic by features, not just files 🔹 Keep components reusable and independent 🔹 Move all API logic into services (no messy calls inside components) 🔹 Use custom hooks to simplify complex logic 🔹 Maintain global state with Context or Redux only when needed 🔹 Keep utilities and helpers isolated for better reuse 💡 The goal is simple: Write code today that’s easy to scale tomorrow. As projects grow, structure becomes more important than syntax. What’s your approach—feature-based or file-based structure? 👇 #ReactJS #FrontendDevelopment #MERNStack #CleanCode #WebDevelopment #Javascript
To view or add a comment, sign in
-
-
React concepts every developer should know 🚀⚛️ If you're learning React, these are some of the most important building blocks: 🔹 Components Reusable pieces of UI. Instead of repeating code, you create small independent blocks like Navbar, Card, Button, etc. 🔹 JSX A syntax that lets you write HTML-like code inside JavaScript. It makes UI creation easier and more readable. 🔹 Props Short for “properties.” Used to pass data from a parent component to a child component. 🔹 useState() A React Hook used to store and update dynamic data inside a component, such as counters, form inputs, toggles, etc. 🔹 useEffect() Used for side effects like fetching APIs, updating the DOM, timers, or reacting to state changes. 🔹 Prop Drilling When data is passed through multiple components just to reach a deeply nested child. This can become hard to manage. 🔹 Context A solution to avoid prop drilling. It allows global sharing of data like themes, authentication, language, etc. 🔹 Reducers Used for managing complex state logic in a predictable way, usually with useReducer(). 💡 Master these concepts and React becomes much easier to understand. #ReactJS #WebDevelopment #Frontend #JavaScript #Coding #SoftwareEngineering #ReactDeveloper #100DaysOfCode
To view or add a comment, sign in
-
-
React Learning Series | Contd... #Day22: Difference between useEffect and useLayoutEffect Most developers use useEffect everywhere ⚛️ But very few truly understand when to use useLayoutEffect 🤔 Here’s the difference in one line 👇 🟢 useEffect → runs AFTER the UI is painted 🟠 useLayoutEffect → runs BEFORE the UI is painted This small timing difference can cause real UI issues 💥 Example: If you measure DOM size using useEffect, users may see a flicker 😬 Switching to useLayoutEffect fixes it instantly ⚡ Rule I follow 👇 ✅ 90% of cases → useEffect ⚠️ Use useLayoutEffect only when layout must be calculated before paint 🚨 Overusing useLayoutEffect can hurt performance since it blocks rendering React is not just about writing components… It’s about understanding when things happen ⏱️ Have you ever faced a UI flicker issue like this? #React #Frontend #JavaScript #WebPerformance
To view or add a comment, sign in
-
Most React tutorials show basic folder structures—but real-world projects need something more scalable. Here’s the approach I follow to keep my projects clean and production-ready: 🔹 I separate logic by features, not just files 🔹 Keep components reusable and independent 🔹 Move all API logic into services (no messy calls inside components) 🔹 Use custom hooks to simplify complex logic 🔹 Maintain global state with Context or Redux only when needed 🔹 Keep utilities and helpers isolated for better reuse 💡 The goal is simple: Write code today that’s easy to scale tomorrow. As projects grow, structure becomes more important than syntax. What’s your approach—feature-based or file-based structure? 👇 #ReactJS #FrontendDevelopment #MERNStack #CleanCode #WebDevelopment #Javascript #NextJS #fblifestyle #IT #Structure #FullStack
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