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!
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!
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 executedelay
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)
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')
setInterval
runs forever, until:
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')
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.