Skip to main content
Saved

Pattern Performance Intermediate

Debounce

With debouncing, your code only reacts once the user stops typing, so an API call or validation runs once instead of on every keystroke.

Examples
React, Vue, Svelte and native web
Read
5 min

The problem

I’ve watched search inputs send an API request on every keystroke as users type “javascript”. That’s ten separate requests, for “j”, “ja”, “jav”, “java”, and so on up to “javascript”, when only the last one is needed. Each extra request adds load to the server, and the responses can arrive out of order, so the wrong results end up on screen.

The pattern

Debouncing delays a function call until events have stopped for a short time. Each event starts a timer, typically of 150-500ms, and if another event comes in before the timer finishes, the debounce code cancels that timer and starts a new one. The function only runs once a timer finishes without being reset.

Problem

The same problem comes up with any event that fires rapidly. A resize handler might recalculate the layout 60 or more times per second and block the main thread. Form validation might show an “email invalid” error as soon as the user has typed “user@”, when they clearly haven’t finished the address yet. All that extra work drains the battery on mobile devices and makes the interface feel slow. Autocomplete dropdowns also flicker as their results change with each keystroke.

Solution

In code, debouncing is just two statements, clearTimeout(timeoutId); timeoutId = setTimeout(fn, delay);, which cancel any pending call and schedule a new one. In a search input, the API request is sent once after typing stops, and in a resize handler, the layout is recalculated once after the user finishes resizing.

Shorter delays of 150-200ms work well for responsive autocomplete, while longer delays of 300-500ms suit slower or heavier API calls, where you’d rather send fewer requests.

The Wrong Choice

Debounce is the wrong choice when users need to see updates while they’re still scrolling or moving the mouse. A scroll-spy that highlights the current section is a classic example. If you debounce the scroll handler, users get no feedback while they scroll, and then they see a sudden jump once they stop, which feels broken.

Throttling works better here. Debounce runs once after the events stop, but throttle runs at regular intervals while the events keep coming, and never more than once in each time window. With a 100ms throttle, the scroll-spy updates about 10 times per second, which looks smooth without running the handler on every scroll event.

Debounce is the better fit when you only need the final value once the activity stops, as with search queries and form validation. Throttle is better when users need feedback while the activity is still going on, as with scroll position and mouse movement.

Example

Basic Debounce Utility

A reusable debounce function wraps the two statements from the Solution section around any function. The cancel method clears a pending call, which a component needs to do when it unmounts.

function debounce(fn, delay) {
  let timeoutId;

  function debounced(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
  }

  debounced.cancel = () => clearTimeout(timeoutId);
  return debounced;
}

Debounced Search Input

The Vue, Svelte, and Web Components versions of this search input all call that debounce function. The React version debounces the value instead of the function. Each change to query starts a timer in an effect, and the effect’s cleanup clears the previous timer, so the pending update is canceled and rescheduled in the same way.

import { useState, useEffect } from 'react';

function useDebouncedValue(value, delay = 300) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timeoutId = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timeoutId);
  }, [value, delay]);

  return debouncedValue;
}

function SearchInput() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const debouncedQuery = useDebouncedValue(query, 300);

  useEffect(() => {
    if (debouncedQuery) {
      fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`)
        .then(res => res.json())
        .then(setResults);
    }
  }, [debouncedQuery]);

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." />
      <ul>{results.map(item => <li key={item.id}>{item.name}</li>)}</ul>
    </div>
  );
}

Debounce with Loading State

You can show a loading indicator while the debounced function is pending, so users know the app is responding to their typing.

function SearchInput() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [isSearching, setIsSearching] = useState(false);
  const debouncedQuery = useDebouncedValue(query, 300);
  // True while the user is typing and the debounced value hasn't caught up yet
  const isPending = query !== debouncedQuery;

  useEffect(() => {
    if (!debouncedQuery) return;
    setIsSearching(true);
    fetch(`/api/search?q=${encodeURIComponent(debouncedQuery)}`)
      .then(res => res.json())
      .then(data => { setResults(data); setIsSearching(false); });
  }, [debouncedQuery]);

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search..." />
      {(isPending || isSearching) && <span>Searching...</span>}
      <ul>{results.map(item => <li key={item.id}>{item.name}</li>)}</ul>
    </div>
  );
}

Debounced Window Resize Handler

For window events that fire rapidly, such as resize, debouncing lets you recalculate the layout once the resize ends instead of on every event.

const debouncedResize = debounce(() => {
  recalculateLayout();
  updateResponsiveElements();
}, 150);

window.addEventListener('resize', debouncedResize);

// Call this when the page or component no longer needs the handler.
function teardown() {
  window.removeEventListener('resize', debouncedResize);
}

Benefits

  • Search inputs send one request after the user pauses instead of ten while they type a single word.
  • A heavy resize handler runs once after the user finishes resizing, instead of dozens of times per second, so the UI stays responsive.
  • Out-of-order responses are less likely, because a request is only sent once the user has paused, not for each half-typed query.
  • Form validation only shows errors once users pause, instead of flagging an address as invalid halfway through typing it.
  • Mobile devices use less battery, because heavy calculations don’t run for each event in a rapid burst.
  • The pattern only takes a few lines of code around clearTimeout and setTimeout, and it doesn’t need any dependencies.

Tradeoffs

  • Feedback is always delayed by at least the debounce delay, regardless of how fast the operation itself is.
  • When you choose a delay, you have to balance responsiveness against the number of requests, because 150ms feels snappy for autocomplete but sends too many requests to a slow API, while 500ms suits server requests but feels slow for simple updates.
  • It’s easy to get the timers wrong, and if you forget to clear timeouts on unmount, a callback can run after the component is gone and update stale state, which is hard to debug.
  • Slow typists might still trigger several requests if they pause for longer than your delay, so debouncing cuts down the number of requests but can’t guarantee there’s only one. When that happens, the first response can still arrive after the second and replace the newer results. Debouncing doesn’t prevent that, so you still need to cancel the earlier request or ignore its response, as the search box in Loading State does with AbortController.
  • The delay can make the interface feel unresponsive, so you’ll often want to show immediate feedback, such as a “searching…” indicator, while the debounced call is pending.
  • Debouncing can’t guarantee that the function runs at regular intervals, because if the user keeps typing without pausing, the function doesn’t run at all until they stop.

Summary

Debouncing delays a call until events have stopped for a short time, and then makes a single call instead of one call for each event. That cuts out most of the wasted work and makes out-of-order responses less likely, though it doesn’t prevent them. Shorter delays of 150-200ms suit responsive feedback, and longer delays of 300-500ms suit heavier operations. You’ll need to clear pending timeouts on unmount, so a callback doesn’t run after its component has unmounted.

See also

Next in Performance Lazy Loading Code and images that only load when users need them, so the first page loads faster and uses less bandwidth.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.