DEV Community

Shashi Bhushan Kumar
Shashi Bhushan Kumar

Posted on

setTimeout(0) Myth Explained Simply

⏳ setTimeout(0) Myth Explained Simply

Many beginners think:

setTimeout(fn, 0);
Enter fullscreen mode Exit fullscreen mode

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:

  1. It goes to Web APIs
  2. Then it moves to the Macrotask Queue
  3. The Event Loop waits until the Call Stack is empty
  4. 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");
Enter fullscreen mode Exit fullscreen mode

✅ Output

Start
End
Timeout
Enter fullscreen mode Exit fullscreen mode

🤔 Why Does "End" Come Before "Timeout"?

Because JavaScript runs in this order:

  1. Synchronous code
  2. Microtasks (Promises)
  3. 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)