JavaScript allows you to execute code at specific time intervals. These are called timing events. Using the window object methods, you can delay code execution or repeat a task over and over with a set time gap.
Interact with the live examples below to see timeouts and intervals in action:
Updates every 1 second (setInterval)
Trigger after 3 seconds (setTimeout)
The setTimeout() method executes a function, after waiting a specified number of milliseconds.
// Executes alert after 3000ms (3 seconds)
setTimeout(function() {
alert("Time is up!");
}, 3000);
The clearTimeout() method stops the execution of the function specified in setTimeout(). You must save the timeout ID to a variable first.
let myTimeout = setTimeout(myFunction, 2000);
// Stop the execution
clearTimeout(myTimeout);
The setInterval() method repeats a given function at every given time-interval.
// Executes myFunction every 1 second
let myInterval = setInterval(myFunction, 1000);
function myFunction() {
console.log("Tick!");
}
The clearInterval() method stops the executions of the function specified in the setInterval() method.
let timer = setInterval(countSeconds, 1000);
// Later, stop the timer
clearInterval(timer);
5000.
| Method | Description | Execution |
|---|---|---|
setTimeout() |
Delays code execution | Runs Once |
setInterval() |
Repeats code execution | Runs Repeatedly |
clearTimeout() |
Cancels a pending timeout | - |
clearInterval() |
Cancels an active interval | - |