setTimeout
Runs a function once after a delay.
Available since: Web API
Syntax
setTimeout(callback, delay, ...args)Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | Function | The function to run once. |
| delay | number | Optional. The delay in milliseconds. 0 by default. |
| ...args | any | Optional. Arguments for the function. |
Return value
numberThe timer id — for cancelling with clearTimeout.
Examples
A delayed call:
setTimeout(() => console.log('one second later'), 1000);
console.log('right now');Output:
right now
one second laterEven a zero delay runs after the current code:
setTimeout(() => console.log('timer'), 0);
console.log('first');
console.log('second');Output:
first
second
timerA pause with a promise:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
console.log('start');
await sleep(300);
console.log('300 ms later');Output:
start
300 ms laterNotes
The delay is a minimum, not an exact time: if the program is busy, the function runs later.
A common mistake is passing a call result instead of a function: setTimeout(greet(), 1000) calls greet immediately. Correct: setTimeout(greet, 1000) or setTimeout(() => greet('Anna'), 1000).
See also
- clearTimeout — Cancels a scheduled setTimeout.
- setInterval — Runs a function again and again at an interval.
- Promise — A promise of a result that will be ready later: success or failure.
Related recipes
In the tutorial
- Timers — The setTimeout and setInterval functions in JavaScript: delayed and repeated calls, arguments, cancelling a timer.