0
0
JavascriptHow-ToBeginner · 3 min read

How to Use setTimeout with 0 Delay in JavaScript

Use setTimeout(function, 0) in JavaScript to delay the execution of function until the current code finishes running. This does not run immediately but schedules the function to run as soon as possible after the current tasks complete.
📐

Syntax

The setTimeout function takes two main arguments: a callback function to run later, and a delay time in milliseconds. When you use 0 as the delay, it means the callback will run after the current code finishes, not instantly.

  • callback: The function you want to run later.
  • delay: Time in milliseconds to wait before running the callback. Using 0 means run as soon as possible after current tasks.
javascript
setTimeout(callback, 0);
💻

Example

This example shows how setTimeout with 0 delay defers a message until after the current synchronous code runs.

javascript
console.log('Start');
setTimeout(() => {
  console.log('Inside setTimeout with 0 delay');
}, 0);
console.log('End');
Output
Start End Inside setTimeout with 0 delay
⚠️

Common Pitfalls

Many expect setTimeout(..., 0) to run the callback immediately, but it always waits until the current code finishes and the event queue is checked. This means it is asynchronous and can cause unexpected order if misunderstood.

Also, some browsers have a minimum delay (usually 4ms) even if you specify 0.

javascript
console.log('Before');
setTimeout(() => console.log('Timeout 0'), 0);
console.log('After');

// Wrong expectation: 'Timeout 0' runs between 'Before' and 'After'
// Correct order is:
// Before
// After
// Timeout 0
Output
Before After Timeout 0
📊

Quick Reference

  • setTimeout(callback, 0): Runs callback after current code finishes.
  • Does not run immediately, but schedules callback asynchronously.
  • Useful to defer work without blocking UI or to break up long tasks.
  • Minimum delay may be greater than 0 due to browser limits.

Key Takeaways

setTimeout with 0 delay schedules code to run after current tasks finish, not immediately.
It helps defer work to avoid blocking the main thread or to reorder execution.
The callback runs asynchronously via the event queue.
Browsers may enforce a minimum delay greater than 0 despite specifying 0.
Expect the callback to run after all synchronous code completes.