Debounce

2 snippets across 2 stacks — JavaScript, React

JSJavaScript

Debounce

JS · Common Patterns
syntax
function debounce(fn, delay) { ... }
example
function debounce(fn, delay) {
  let timerId;
  return function (...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Usage: only fire after user stops typing for 300ms
const searchInput = document.querySelector("#search");
searchInput.addEventListener("input",
  debounce((e) => {
    console.log("Searching:", e.target.value);
  }, 300)
);

Note Debouncing delays execution until activity stops for a given period. Ideal for search inputs, window resize handlers, and form validation.

REReact

Storing Timer IDs

RE · useRef
syntax
const timerRef = useRef(null);
// Start
timerRef.current = setTimeout(fn, ms);
// Clear
clearTimeout(timerRef.current);
example
function DebouncedSearch({ onSearch }) {
  const [query, setQuery] = useState('');
  const timerRef = useRef(null);

  function handleChange(e) {
    const value = e.target.value;
    setQuery(value);

    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      onSearch(value);
    }, 400);
  }

  useEffect(() => {
    return () => clearTimeout(timerRef.current);
  }, []);

  return <input value={query} onChange={handleChange} />;
}

Note Store timer IDs in a ref so they survive re-renders without causing them. Always clear the timer on unmount via useEffect cleanup to prevent firing after the component is gone.