JavaScript Reference ยท Promises and Async
The setTimeout() function
Reference for JavaScript setTimeout(): scheduling a callback after a delay, passing arguments, timer ids, minimum delays and pitfalls, with live examples.
setTimeout() schedules a function to run once after at least the given number of milliseconds. It returns immediately with a timer id; the callback runs later, when the delay has passed and the JavaScript thread is free.
It is not part of the language itself but of the host environment, and it is available in browsers (as window.setTimeout), in Web Workers and in Node.js.
const id = setTimeout(() => console.log("later"), 1000);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
setTimeout(callback) setTimeout(callback, delay) setTimeout(callback, delay, arg1, arg2, /* โฆ, */ argN)
| Name | Description |
|---|---|
callback |
The function to call. Pass a function, not the result of calling one. |
delay |
Milliseconds to wait. Optional; defaults to 0. Non-numbers are converted; negative values count as 0. |
arg1 โฆ argN |
Extra arguments passed to callback when it runs. |
Return value: a timer id you can pass to clearTimeout(). In browsers it is a positive integer; in Node.js it is a Timeout object (which can also be passed to clearTimeout()).
Usage notes
- The delay is a minimum. The callback waits until the current script and any queued microtasks have finished. A long synchronous loop delays every timer. See the event loop.
setTimeout(fn, 0)is not immediate. The callback is a separate task that runs after the current code and after promise callbacks. Browsers may also clamp deeply nested timers to a few milliseconds.- Background tabs throttle timers, often to once per second or less. Do not use timers to measure real time; compare timestamps instead.
- Common mistake:
setTimeout(doWork(), 1000)callsdoWorkright away and schedules its return value. WritesetTimeout(doWork, 1000)orsetTimeout(() => doWork(), 1000). thisinside the callback is not the object you scheduled from when you pass a regular method. Use an arrow function orbind().- Passing a string (
setTimeout("code()", 100)) evaluates it likeeval()and is blocked by strict Content Security Policies. Never do it. - Maximum delay. The delay is stored in a 32-bit signed integer, so values above about 24.8 days (2,147,483,647 ms) overflow and fire almost immediately.
- Recursive
setTimeout()is often better thansetInterval()for repeating work, because the next delay starts after the previous run finishes. - Promises. Wrap it in
new Promiseto get asleep()helper that works withawait, as in the second example.
Browser support
setTimeout() is supported by every browser and by Node.js. Passing extra arguments after the delay works in all current browsers.