setTimeout() and setInterval() in JavaScript
Last updated: September 27, 2022.
setTimeout()
and setInterval()
are globally available functions in JavaScript.
setTimeout()
delays the execution of code by a specified amount of time. setInterval()
repeatedly runs some code at a given interval.
Table of contents
setTimeout()
setTimeout()
accepts two arguments.
The first is a function definition and the second is a specified time delay in milliseconds. After the time delay, the function is executed:
setTimeout(() => {
console.log("Time's up!"); // logged after 1 second
},1000);
Instead of writing a function in the first position, you can reference a function:
setTimeout(logMsg, 1000);
function logMsg() {
console.log("Time's up!"); // logged after 1 second
};
Optionally, you can add additional arguments that can be used inside the setTimeout()
function:
setTimeout((x, y, z) => {
console.log([x, y, z]);
},1000, "x", 1 , true);
Cancelling with clearTimeout()
Each time you call setTimeout()
, it returns a unique ID.
By passing this value into clearTimeout()
, you can cancel a setTimeout()
before it occurs:
const timeoutID = setTimeout(() => {
console.log("Time's up!");
},1000);
clearTimeout(timeoutID);
In the above example, nothing is logged to the console because timeout t is cancelled immediately after it is created.
setInterval()
Similarly, you pass a function to setInterval()
as a first argument. The second argument is the interval of time between function calls:
setInterval(() => {
console.log("This never gets boring"); // keeps logging every second indefinitely
},1000);
You may also choose to separate the function from the setInterval()
call:
setInterval(logMsg, 1000);
function logMsg() {
console.log("This never gets boring"); // keeps logging indefinitely
};
You can also pass additional argument to setInterval()
that are then available as arguments within the first position function:
const msg = "This never gets boring";
setInterval((x) => {
console.log(x)
},1000, msg);
Cancelling with clearInterval()
setInterval()
also returns a unique ID when it is called, which can be used to cancel it by calling clearInterval()
and passing in the ID:
const msg = "This never gets boring";
const intervalID = setInterval((x) => {
console.log(x); // Runs five times
},1000, msg);
setTimeout(() => {
clearInterval(intervalID); // Then is cancelled
},5000);