JavaScript delay handling

delaying and repeating events based on time

// updated 2025-05-09 08:09

At times, we may wish to use:

  • setTimeout
    • to delay an event
  • setInterval
    • repeat an event at regular intervals
    • clearInterval will 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 (for setInterval)
    • a number in milliseconds

setTimeout

The syntax should look intuitive:

1setTimeout(function() { 
2  console.log('This gets logged to the console after 5 seconds') 
3}, 5000)
4
5// alternatively
6const logLate = () => 
7  console.log('This gets logged to the console after 5 seconds')
8setTimeout(logLate, 5000)

setInterval

Essentially the same syntax as setTimeout but with a different name and result:

1setInterval(function() { 
2  console.log('This will log onto the console every 5 seconds') 
3}, 5000)
4
5// alternatively
6const keepLogging = () => 
7  console.log('This will log onto the console every 5 seconds')
8setInterval(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:

1const myInterval = setInterval(function() {
2  console.log('This will log onto the console every 5 seconds')
3}, 5000) 
4
5setTimeout(function() {
6  clearInterval(myInterval)
7  console.log('The interval has stopped after 50 seconds')
8}, 50000) 

⬅️ older (in textbook-javascript)
📒 JavaScript DOM access
newer (in textbook-javascript) ➡️
JavaScript data fetching 📒
⬅️ older (in code)
📒 JavaScript DOM access
newer (in code) ➡️
JavaScript data fetching 📒
⬅️ older (posts)
📒 JavaScript DOM access
newer (posts) ➡️
JavaScript data fetching 📒