ESC

Type to search the knowledge base.

SnippetJavaScript

Debounce

Delay invoking a function until after a quiet period — search inputs, resize handlers, autosave.

Explanation

Debounce resets a timer on every call and only runs the function after `wait` ms of silence. Leading-edge variants exist; this is the common trailing form.

javascript
export function debounce(fn, wait = 300) {
  let timer;
  function debounced(...args) {
    const ctx = this;
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(ctx, args), wait);
  }
  debounced.cancel = () => clearTimeout(timer);
  return debounced;
}

Usage example

javascript
const onSearch = debounce((q) => {
  fetch(`/api/search?q=${encodeURIComponent(q)}`);
}, 300);

input.addEventListener('input', (e) => onSearch(e.target.value));
// on unmount: onSearch.cancel()

Interview tips

  • Contrast with throttle: debounce waits for quiet; throttle caps rate while events fire.
  • Always discuss cancel/cleanup in React (useEffect).

Related

← All snippets