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.

Frequently asked questions

How does JavaScript handle debounce?
This task is covered in 2 stacks on this page: JavaScript, React. The "Debounce" snippet in JavaScript uses `function debounce(fn, delay) { ... }`.
Which code does the JavaScript example use?
The "Debounce" snippet uses `function debounce(fn, delay) { ... }`, from the Common Patterns section of the JavaScript cheat sheet.
Which stacks cover "debounce" on this page?
JavaScript, React. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Debounce": Debouncing delays execution until activity stops for a given period. Ideal for search inputs, window resize handlers, and form validation.