setInterval

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

setInterval

setTimeout lets you execute a callback after X milliseconds. setInterval lets you execute a callback every X milliseconds.

setInterval(callback, delay)
  • callback is the function you want to execute
  • delay is the number of milliseconds before JavaScript calls the callback

Here’s an example. Let’s say you want to start a count from 0. After each second, you want to increase the count by 1.

let count = 0
setInterval(() => {
  count = count + 1
  console.log(count)
}, 1000)
Logs count. Count increases by 1 every one second.

Additional parameters

If you want to send additional arguments to setInterval, you can do so after writing delay.

let count = -1
const callTheAvengers = (...superheroes) => {
  count = count + 1
  console.log(`${superheroes[count]} has arrived!`)
}

setInterval(callTheAvengers, 1000, 'Iron Man', 'Hulk', 'Thor')
Logs one avenger arriving every second. From the fourth second onwards, logs 'undefined has arrived'.

Cancelling an interval

setInterval runs forever, until:

  1. The user leaves the page
  2. You call clearInterval

Like setTimeout, setInterval returns an id. You can use this id to clear the interval.

let count = -1
const callTheAvengers = (...superheroes) => {
  count = count + 1
  if (!superheroes[count]) return clearInterval(id)
  console.log(`${superheroes[count]} has arrived!`)
}

const id = setInterval(callTheAvengers, 1000, 'Iron Man', 'Hulk', 'Thor')
Logs one superhero each second. Stops logging after all three superheroes have been logged.

1000 milliseconds might not be 1 second

Again, if you set delay to 1000, it does not mean JavaScript will always execute callback every second. JavaScript will only execute callback when it’s free.