setInterval()

Calls a function repeatedly, at the given interval, until it’s stopped with clearInterval().

Returns
An interval id to use with clearInterval().
On this page

Example

#
JavaScript
let seconds = 3

const countdown = setInterval(() => {
  console.log(seconds)
  seconds -= 1

  if (seconds === 0) {
    clearInterval(countdown)
    console.log('Mission start!')
  }
}, 300)
Console
3
2
1
Mission start!

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

#
Syntax
const intervalId = setInterval(callback, delay)
setInterval(callback, delay, arg1, arg2, …)

clearInterval(intervalId)

Parameters

#
  • callback

    function

    The function called every delay milliseconds.
  • delay

    a number

    The interval between calls, in milliseconds.
  • arg1…argN

    optional

    Arguments passed to the function on every call.

More examples

#
Progress that stops at 100%
JavaScript
let progress = 0

const loader = setInterval(() => {
  progress += 25
  console.log(`Loading: ${progress}%`)
  if (progress >= 100) clearInterval(loader)
}, 200)
Console
Loading: 25%
Loading: 50%
Loading: 75%
Loading: 100%
A setTimeout() chain instead of an interval
JavaScript
let attempt = 1

function checkStatus() {
  console.log(`Checking status, attempt ${attempt}`)
  attempt += 1
  if (attempt <= 3) setTimeout(checkStatus, 200)
}

checkStatus()
Console
Checking status, attempt 1
Checking status, attempt 2
Checking status, attempt 3

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(), not setInterval().

Related entries

#

Spotted a mistake or missing an example? Write to us.