setTimeout lets you execute a callback after X milliseconds. setInterval lets you execute a callback every X milliseconds.
setInterval(callback, delay)callbackis the function you want to executedelayis the number of milliseconds before JavaScript calls thecallback
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 = 0setInterval(() => { count = count + 1 console.log(count)}, 1000)
Additional parameters
If you want to send additional arguments to setInterval, you can do so after writing delay.
let count = -1function callTheAvengers(...superheroes) { count = count + 1 console.log(`${superheroes[count]} has arrived!`)}
setInterval(callTheAvengers, 1000, 'Iron Man', 'Hulk', 'Thor')
Cancelling an interval
setInterval runs forever, until:
- The user leaves the page
- You call
clearInterval
Like setTimeout, setInterval returns an id. You can use this id to clear the interval.
let count = -1function 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')
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.
Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson