Skip to content
GreenSnippets

Debounce a function

Delay a function call until the caller has stopped invoking it for a given time, with cancel support.

JavaScript
function debounce(fn, wait = 200) {
  let timer;
  function debounced(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), wait);
  }
  debounced.cancel = () => clearTimeout(timer);
  return debounced;
}

Example / expected output

Output
// Rapid calls "a", "ab", "abc" within 200ms -> fn runs once with "abc"

How it works

Debouncing collapses a burst of calls (typing, resizing, scrolling) into a single call that runs after the burst has been quiet for wait milliseconds. Use it for search-as-you-type or autosave.

  • The returned function keeps the latest arguments and this.
  • Call .cancel() when a component unmounts so a pending call cannot fire late.
  • If you need the first call to run immediately, you want throttling instead.