setTimeout and setInterval in JavaScript
Running code later, or over and over, with setTimeout and setInterval.
There are times when you need to run code later, like hiding a notification
after a few seconds, or over and over, like updating a clock. JavaScript has two
functions for this: setTimeout and setInterval.
setTimeout runs a function once after a delay. setInterval runs a function
repeatedly, waiting the delay between each run.
setTimeout
Pass a function and a delay in milliseconds:
setTimeout(() => {console.log("Runs after 2 seconds")}, 2000)
The delay is the minimum wait, not an exact time. If the browser is busy, the function may run a little later.
Cancelling a Timeout
setTimeout returns an id. Pass it to clearTimeout to cancel the timeout
before it runs:
const timeoutId = setTimeout(() => {hideNotification()}, 5000)closeButton.addEventListener("click", () => {clearTimeout(timeoutId)hideNotification()})
If the user closes the notification early, the timeout is cancelled so
hideNotification doesn't run a second time.
setInterval
setInterval takes the same arguments but keeps running until you stop it with
clearInterval:
const intervalId = setInterval(() => {console.log(new Date().toLocaleTimeString())}, 1000)// laterclearInterval(intervalId)
This logs the time every second.
A Countdown Example
Putting the two together, here's a countdown that stops itself when it hits zero:
const countdown = document.querySelector("#countdown")let seconds = 10countdown.textContent = secondsconst intervalId = setInterval(() => {seconds -= 1countdown.textContent = secondsif (seconds === 0) {clearInterval(intervalId)countdown.textContent = "Go!"}}, 1000)
Note: Always clear an interval when you're done with it. Otherwise it keeps running in the background for as long as the page is open.
What a Delay of 0 Means
A delay of 0 doesn't run the function right away. It waits until the code
that's running now has finished:
setTimeout(() => console.log("second"), 0)console.log("first")// console: first// console: second
This is handy when you need something to happen right after the current work, like after the browser has updated the page.
Use setTimeout for one-off delays, setInterval for repeats, and keep the id
around so you can clear them.
Have some feedback on this post? .