setTimeout vs setInterval in JavaScript

setTimeout runs a function once after a delay; setInterval repeats it on a fixed cycle. Learn the difference, drift issues, and how to clear each one.

Published September 16, 2026

setTimeout(fn, delay) schedules fn to run once after delay milliseconds. setInterval(fn, delay) schedules fn to run repeatedly every delay milliseconds until explicitly stopped.

Common causes

  • setInterval doesn't account for how long fn itself takes to run — if fn takes longer than delay, calls can queue up or overlap in some environments
  • Both timers are minimums, not guarantees — the browser or Node event loop can delay execution if the main thread is busy

How to fix it

  • For repeating work where drift matters, prefer a recursive setTimeout — schedule the next call only after the current one finishes
  • Always store the return value (a timer ID) and call clearTimeout()/clearInterval() when the timer is no longer needed, especially in component unmount/cleanup code
  • Use setInterval only for simple, lightweight repeating tasks where slight timing drift is acceptable

Example

function poll() {
  doWork()
  setTimeout(poll, 1000)
}
poll()

FAQ

Why is recursive setTimeout better than setInterval for polling?

It guarantees the delay is measured from when the previous call finished, not from a fixed schedule — so slow work never causes overlapping executions.

More JavaScript articles