Bhushan Mayekar’s Post

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

  • graphical user interface

To view or add a comment, sign in

Explore content categories