ComparisonComparisons

setTimeout() vs setInterval()

setTimeout() calls a function once after a set amount of time, while setInterval() calls it repeatedly until you stop it with clearInterval().

On this page

Side-by-side comparison

#

Example

#
JavaScript
console.log('Start')

const timer = setInterval(() => console.log('Interval tick'), 200)

setTimeout(() => {
  clearInterval(timer)
  console.log('Timeout after 500 ms, interval stopped')
}, 500)
Console
Start
Interval tick
Interval tick
Timeout after 500 ms, interval stopped

Definition and usage

#

Both functions schedule a callback after the given number of milliseconds and don’t block the rest of the code, which keeps running right away. Both return an identifier, which you pass to the matching cleanup function to cancel the scheduled call. The given time is only a minimum delay, not a guarantee of precision.

setTimeout() calls the function once and is done. setInterval() calls it repeatedly, at the same interval, until clearInterval() is called, and the first call also happens after the first interval, not right away. A forgotten interval keeps running forever, even once no one needs its results anymore, which is a common cause of memory leaks. When a single call can take longer than the interval, for example a request to a server, a self-scheduling chain of setTimeout() calls is safer.

Use setTimeout() for a one-off delay and for debounce-style mechanisms. For simple, fixed repetition, like a countdown, setInterval() is enough, but remember clearInterval() once it’s no longer needed.

Syntax

#
Syntax
const timeoutId = setTimeout(callback, delay)
const intervalId = setInterval(callback, delay)

More examples

#
Counting interval calls
JavaScript
let calls = 0

const id = setInterval(() => {
  calls += 1
  if (calls === 3) {
    clearInterval(id)
    console.log('Total calls:', calls)
  }
}, 150)
Console
Total calls: 3
Debounce built on setTimeout()
JavaScript
function debounce(fn, ms) {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => fn(...args), ms)
  }
}

const saveDraft = debounce((text) => console.log('Draft saved:', text), 200)

saveDraft('H')
saveDraft('He')
saveDraft('Hello')
Console
Draft saved: Hello

Every call to saveDraft() clears the previous timer with clearTimeout(). Only the last draft gets saved, 200 ms after the last call.

Good practices

#
  • Always save the identifier returned by setInterval() and call clearInterval() once the repetition is no longer needed.
  • When a single call can take longer than the interval, for example a request to a server, use a chain of setTimeout() instead of setInterval().
  • For debounce (reacting after a pause in typing), build on setTimeout(), not setInterval().

Related entries

#

Spotted a mistake or missing an example? Write to us.