These are both timers in JavaScript. For some reason I always used to get these two confused, even though there's a clue in the name as to which does which.
setInterval
This is used to do something repeatedly after a certain amount of time.
setInterval(runFunction, 1000)
This will run the function called runFunction every 1000 milliseconds, ie 1 second. It will keep doing it until you tell it to stop.
To stop it you use clearInterval - but you have to have given the setInterval a name first.
let interval;
document.querySelector('.startButton').addEventListener('click', function() {
interval = setInterval(runFunction, 1000)
})
document.querySelector('.stopButton').addEventListener('click', function() {
clearInterval(interval)
})
function runFunction() {
console.log('Running!')
}
This will print "Running!" to the console every second after you press the startButton, and stop once you press the stopButton.
You don't have to run a function from setInterval, you can use an anonymous function:
setInterval( function() {
console.log('Running!')
}, 1000 )
Or with an arrow function:
setInterval( () => {
console.log('Running!')
}, 1000 )
setTimeout
This is used to do something after a certain amount of time and then stop. So this will print "Running!" to the console once after 1 second:
setTimeout( () => {
console.log('Running!')
}, 1000 )
Similarly, you can clear the interval afterwards:
const timeout = setTimeout(runFunction, 1000)
function runFunction() {
console.log('Running!')
clearTimeout(timeout)
}
Conclusion
setInterval and setTimeout are very similarly structured. The main difference is that setTimeout runs once after the timer times out and setInterval runs multiple times on the interval set.
Top comments (0)