setInterval()
Calls a function repeatedly, at the given interval, until it’s stopped with clearInterval().
- Returns
- An interval id to use with
clearInterval().
Example
#let seconds = 3
const countdown = setInterval(() => {
console.log(seconds)
seconds -= 1
if (seconds === 0) {
clearInterval(countdown)
console.log('Mission start!')
}
}, 300)Definition and usage
#The setInterval() function runs the given function repeatedly, each time after the same interval in milliseconds has passed. The first call happens only after the first interval, not right away.
It returns an id that you pass to clearInterval() to stop the repetition. Without that, the function keeps getting called forever, even after nobody needs its results anymore. A forgotten interval is a common cause of memory leaks and hard-to-find bugs.
The interval isn’t perfectly precise. When the browser is busy or the tab is running in the background, calls can be delayed. So for countdowns, calculate elapsed time from Date.now(), and for animations, use requestAnimationFrame().
Syntax
#const intervalId = setInterval(callback, delay)
setInterval(callback, delay, arg1, arg2, …)
clearInterval(intervalId)Parameters
#callback
function
The function called everydelaymilliseconds.delay
a number
The interval between calls, in milliseconds.arg1…argN
optional
Arguments passed to the function on every call.
More examples
#let progress = 0
const loader = setInterval(() => {
progress += 25
console.log(`Loading: ${progress}%`)
if (progress >= 100) clearInterval(loader)
}, 200)let attempt = 1
function checkStatus() {
console.log(`Checking status, attempt ${attempt}`)
attempt += 1
if (attempt <= 3) setTimeout(checkStatus, 200)
}
checkStatus()The next call is only scheduled after the previous one finishes, so calls never overlap. It’s a good pattern for polling a server whose response time can vary.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Always save the id and call
clearInterval()once the repetition is no longer needed, for example after a countdown finishes or the view is left. - If a single call might take longer than the interval (such as a request to a server), use a
setTimeout()chain so the calls don’t overlap. - For smooth animations, use
requestAnimationFrame(), notsetInterval().
Related entries
#- setTimeout() vs setInterval()setTimeout() calls a function once after a set amount of time, while setInterval() calls it repeatedly until you stop it with clearInterval().
- setTimeout()Runs a function once, after the given number of milliseconds has passed.
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
- DateAn object representing a specific moment in time, with methods to read and change the date and time.
- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
Spotted a mistake or missing an example? Write to us.