Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. setTimeout() / clearTimeout()

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

ArgumentDescription
functionThe callback function to execute after the delay.
millisecondsThe 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

Chrome Chrome
49+
Supported in all versions
Firefox Firefox
57+
Supported in all versions
Safari Safari
18+
Supported in all versions
Edge Edge
80+
11 or earlier ×
IE IE
11+
3 or earlier ×
Opera Opera
48+
3 or earlier ×
iOS Safari iOS Safari
18+
Supported in all versions
Android Browser Android Browser
37+
4 or earlier ×
Chrome Android Chrome Android
36+
17 or earlier ×
Firefox Android Firefox Android
79+
3 or earlier ×

If you find any errors or copyright issues, please .