⏳ setTimeout(0) Myth Explained Simply
Many beginners think:
setTimeout(fn, 0);
means the function runs immediately.
❌ Wrong.
It does NOT run instantly.
🧠 Why?
Because setTimeout is a Macrotask.
Even if the delay is 0, this is what happens:
- It goes to Web APIs
- Then it moves to the Macrotask Queue
- The Event Loop waits until the Call Stack is empty
- Then it executes
So 0 does NOT mean “run now”.
It means “run after current work is finished.”
💻 Example
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
✅ Output
Start
End
Timeout
🤔 Why Does "End" Come Before "Timeout"?
Because JavaScript runs in this order:
- Synchronous code
- Microtasks (Promises)
- Macrotasks (setTimeout)
Since setTimeout is a macrotask,
it waits for the call stack to clear.
🍽 Simple Real-Life Example
Imagine you say:
“Call me after 0 minutes.”
Does that mean the person calls you immediately?
No.
It means:
👉 “Call me after whatever I’m doing right now is finished.”
That’s exactly how setTimeout(0) works.
🎯 Interview Point
setTimeout(0) does NOT mean immediate execution.
It means:
“Run after the current call stack is cleared.”
Top comments (0)