Async JavaScript

Timers, Scheduling & Debouncing

Timers schedule future tasks, but they are not precise clocks. Debouncing and throttling shape frequent events so expensive work runs at a controlled rate.
  • Timer delay is a minimum, not a guarantee
  • Debounce waits for quiet
  • Throttle enforces a maximum rate
  • Intervals can overlap conceptually
  • Fake timers make time testable
Scheduling patterns
PatternBehaviorBest for
setTimeoutRun once after delayTimeouts, delayed work
setIntervalRun repeatedlySimple polling
DebounceRun after quiet periodSearch input
ThrottleRun at most every N msScroll/drag events
requestAnimationFrameBefore browser paintVisual updates
Debounce
function debounce(fn, delay) {
  let id
  return (...args) => {
    clearTimeout(id)
    id = setTimeout(() => fn(...args), delay)
  }
}

const search = debounce((query) => fetchResults(query), 300)
Every call resets the timer; only the final quiet-period call runs.
Sources
  • MDN JavaScript Guide and ReferenceTimers and scheduling APIs
  • The Modern JavaScript TutorialScheduling
  • Node.js Documentation and Learn Node.jsDiscover JavaScript Timers