The JavaScript setTimeout() method
The setTimeout() method runs a function once after a delay given in milliseconds. setTimeout(() => alert("Hi"), 2000) waits two seconds, then runs. It returns a timer id you can pass to clearTimeout() to cancel. The delay is a minimum, not a guarantee — the callback runs after the current code finishes.
Overview
setTimeout() schedules a function to run once, later. You pass the function and a delay in milliseconds (so 1000 is one second), and after that time the function is queued to run. It's how you defer work — show a message after a pause, retry after a delay, debounce rapid input.
It returns a numeric timer id, and that id is your cancel handle: const t = setTimeout(fn, 5000); clearTimeout(t); stops it before it fires. Any arguments after the delay are passed along to your callback when it runs.
Two things commonly surprise people. First, the delay is a minimum, not exact: JavaScript is single-threaded, so the callback waits until the current code and earlier tasks finish — a busy thread can push it later than you asked. Second, setTimeout(fn, 0) doesn't run immediately; it defers fn until after the current script, a useful trick for letting the browser update first. For something that repeats on an interval, use setInterval() instead.
Syntax
const id = setTimeout(callback, delay)
const id = setTimeout(callback, delay, arg1, arg2)
const id = setTimeout(() => console.log("later"), 1000);
clearTimeout(id); // cancel it
Parameters
The setTimeout() method accepts the following parameters.
| Parameter | Description |
|---|---|
callback |
The function to run after the delay. |
delay |
Time to wait in milliseconds before running (a minimum, not exact). Defaults to 0. |
arg1 ... argN |
Optional. Extra arguments passed to the callback when it runs. |
Example
<p id="out" style="font:15px system-ui">Waiting 2 seconds...</p>
<script>
setTimeout(() => {
document.getElementById('out').textContent = 'Done! Two seconds passed.';
document.getElementById('out').style.color = '#16a34a';
}, 2000);
</script>
Best practices
- Remember the delay is in milliseconds and is a minimum — not a precise guarantee.
- Keep the returned id and call
clearTimeout(id)to cancel a pending timeout. - Use
setTimeout(fn, 0)to defer work until after the current code runs. - For repeating work, use setInterval() rather than re-scheduling manually (unless you need precise spacing).
Frequently asked questions
How do I delay code in JavaScript?
setTimeout(callback, delay) with the delay in milliseconds, e.g. setTimeout(fn, 2000) for two seconds.How do I cancel a setTimeout()?
clearTimeout(id) before the delay elapses.Is the setTimeout() delay exact?
What is the difference between setTimeout() and setInterval()?
setTimeout() runs once after a delay; setInterval() runs repeatedly every interval until cleared.