setTimeout() / clearTimeout()
Executes a function once after a specified amount of time has elapsed. You can cancel it before it runs using clearTimeout().
Syntax
// Executes a function after the specified delay. var timerID = setTimeout(function, milliseconds); // Cancels the timer. clearTimeout(timerID);
Arguments
| Argument | Description |
|---|---|
| function | The callback function to execute after the delay. |
| milliseconds | The time to wait before executing, in milliseconds. 1000 milliseconds equals 1 second. If omitted, defaults to 0, and the function runs as soon as possible. |
Return Value
Returns a numeric ID that identifies the timer. Pass this ID to clearTimeout() to cancel the timer.
Sample Code
// Displays a message after 3 seconds.
setTimeout(function() {
console.log("3 seconds have passed");
}, 3000);
// Example of canceling a timer.
var timerID = setTimeout(function() {
console.log("This will not run");
}, 5000);
clearTimeout(timerID); // Canceled before it runs.
// To pass arguments, reference variables inside the function.
var name = "Taro";
setTimeout(function() {
console.log("Hello, " + name + "!"); // Outputs "Hello, Taro!"
}, 1000);
Overview
setTimeout() is a timer function that executes a function exactly once after a specified number of milliseconds. It is commonly used to display a message after a page loads, or to delay an action after user interaction.
Because setTimeout() returns a timer ID, you can cancel execution before it fires by passing that ID to clearTimeout(). For example, it is widely used in a technique called "debouncing," where a search operation is delayed while the user is typing and only runs after a certain period of inactivity.
The delay specified in setTimeout() represents the minimum time to wait — execution at exactly that time is not guaranteed. Depending on the browser's workload, the function may run later than specified. If you need to repeat an operation at a fixed interval, use setInterval() instead.
Browser Compatibility
3 or earlier ×
3 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.