setTimeout
Sets a timer which executes a function or specified piece of code once the timer expires
Syntax
setTimeout(callback, delay?, ...args)Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | Function | A function to be executed after the timer expires |
| delay | number | Time in milliseconds to wait before executing. Defaults to 0 |
| args | any[] | Additional arguments passed to the callback |
Return Value
A positive integer ID that identifies the timer (use with clearTimeout to cancel)
Examples
const id = setTimeout(() => {
console.log('Executed after 1 second');
}, 1000);function debounce<T extends (...args: unknown[]) => void>(fn: T, ms: number) {
let timer: ReturnType<typeof setTimeout>;
return (...args: Parameters<T>) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}console.log('1');
setTimeout(() => console.log('3'), 0);
console.log('2');
// Output: 1, 2, 3Understanding setTimeout
The setTimeout method in JavaScript sets a timer which executes a function or specified piece of code once the timer expires. It belongs to the window object and is one of the most widely used methods for working with window values in modern JavaScript and TypeScript applications.
The method signature is setTimeout(callback, delay?, ...args). It accepts 3 parameters: callback, delay, args. When called, it returns a positive integer id that identifies the timer (use with cleartimeout to cancel). Understanding when and how to use setTimeout() helps you write more expressive, readable code.
Common use cases for setTimeout include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like window-cleartimeout, window-setinterval, window-clearinterval, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for setTimeout is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
More Global / Window Methods
Other methods in the Global / Window object
Related Tools
More Global / Window Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.