JavaScript delay handling
delaying and repeating events based on time
// updated 2025-11-09 15:09
At times, we may wish to use:
setTimeout- to delay an event
setInterval- repeat an event at regular intervals
clearIntervalwill stop the repeating
Each of these methods take in two arguments:
- a function to perform after the delay/interval
- a delay (for
setTimeout) or interval (forsetInterval)- a number in milliseconds
setTimeout
The syntax should look intuitive:
setTimeout(function() {
console.log('This gets logged to the console after 5 seconds')
}, 5000)
// alternatively
const logLate = () =>
console.log('This gets logged to the console after 5 seconds')
setTimeout(logLate, 5000)setInterval
Essentially the same syntax as setTimeout but with a different name and result:
setInterval(function() {
console.log('This will log onto the console every 5 seconds')
}, 5000)
// alternatively
const keepLogging = () =>
console.log('This will log onto the console every 5 seconds')
setInterval(keepLogging, 5000)clearInterval
We may also stop the function that is setInterval-ed after a given amount of time by passing it into a call to the clearInterval method:
const myInterval = setInterval(function() {
console.log('This will log onto the console every 5 seconds')
}, 5000)
setTimeout(function() {
clearInterval(myInterval)
console.log('The interval has stopped after 50 seconds')
}, 50000)