Use clearTimeout(myTimeout) to prevent myGreeting from running:
const myTimeout = setTimeout(myGreeting, 5000);
function myStopFunction() {
clearTimeout(myTimeout);
Try it Yourself »
More examples below.
Description
The
setTimeout()
method calls a function after a number of milliseconds.
1 second = 1000 milliseconds.
Notes
The
setTimeout()
is executed only once.
If you need repeated executions, use
setInterval()
instead.
Use the
clearTimeout()
method to prevent the function from starting.
To clear a timeout, use the
id
returned from setTimeout():
myTimeout = setTimeout(
function
,
milliseconds
);
Then you can to stop the execution by calling clearTimeout():
clearTimeout(myTimeout);
See Also:
The clearTimeout() Method
The setInterval() Method
The clearInterval() Method
milliseconds
Optional.
Number of milliseconds to wait before executing.
Default value is 0.
param1,
param2,
...
Optional.
Parameters to pass to the
function.
Not supported in IE9 and earlier.
Return Value
Description
A numberThe id of the timer.
Use this id with clearTimeout(id) to cancel the timer.
function myFunction() {
timeout = setTimeout(alertFunc, 3000);
}
function alertFunc() {
alert("Hello!");
}
Try it Yourself »
Display a timed text:
let x = document.getElementById("txt");
setTimeout(function(){ x.value = "2 seconds" }, 2000);
setTimeout(function(){ x.value = "4 seconds" }, 4000);
setTimeout(function(){ x.value = "6 seconds" }, 6000);
Try it Yourself »
Open a new window and close the window after three seconds (3000
milliseconds):
const myWindow = window.open("", "", "width=200, height=100");
setTimeout(function() {myWindow.close()}, 3000);
Try it Yourself »
Count forever - but with the ability to stop the count:
function startCount()
function stopCount()
Try it Yourself »
A clock created with timing events:
function startTime() {
const date = new Date();
document.getElementById("txt").innerHTML = date.toLocaleTimeString();
setTimeout(function() {startTime()}, 1000);
Try it Yourself »
Pass parameters to the function (does not work in IE9 and earlier):
setTimeout(myFunc, 2000, "param1", "param2");
Try it Yourself »
However, if you use an anonymous function, it will work in all browsers:
setTimeout(function() {myFunc("param1", "param2")}, 2000);
Try it Yourself »
Browser Support
setTimeout()
is supported in all browsers:
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our
terms of use
,
cookie and privacy policy
.
W3Schools is Powered by W3.CSS
.