Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Debounce vs Throttle in JavaScript: Differences, Code and Use Cases

Understand debounce and throttle in JavaScript with timelines, from-scratch implementations, leading and trailing options, React hooks and real use cases like search boxes, scrolling and resizing.

Sumit KumarUpdated Oct 11, 20264 min readJavaScript
Debounce vs Throttle in JavaScript: Differences, Code and Use Cases

Some browser events fire dozens of times a second: input, scroll, resize, mousemove. If each one triggers an API call or a heavy layout calculation, your app becomes slow and your server gets flooded. Debounce and throttle are two simple techniques that limit how often a function runs.

The difference at a glance#

Debounce vs throttle timeline: raw events, debounced calls firing after a pause, and throttled calls firing at fixed intervals
DebounceThrottle
RuleRun only after events stop for N msRun at most once every N ms
During a continuous burstNever runs until the burst endsRuns at a steady rate
Typical useSearch-as-you-type, auto-save, form validationScroll position, infinite scroll, drag, game input
AnalogyA lift that waits until people stop enteringA train that leaves every 10 minutes no matter what

Debounce from scratch#

JavaScript
function debounce(fn, delay = 300) {
  let timerId;
  return function (...args) {
    clearTimeout(timerId);                       // cancel the previous wait
    timerId = setTimeout(() => fn.apply(this, args), delay);
  };
}

Every call resets the timer. The function only runs once the calls have stopped for delay milliseconds. The closure keeps timerId alive between calls.

Search box example#

JavaScript
const input = document.querySelector("#search");

async function search(query) {
  if (!query.trim()) return;
  const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
  renderResults(await res.json());
}

input.addEventListener("input", debounce((e) => search(e.target.value), 400));

Typing "javascript" fires 10 input events, but only one request goes out, 400 ms after the last keystroke.

Throttle from scratch#

JavaScript
function throttle(fn, interval = 200) {
  let lastRun = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastRun >= interval) {
      lastRun = now;
      fn.apply(this, args);
    }
  };
}

This version runs immediately on the first call, then ignores calls until interval has passed. The catch: the last event in a burst may be dropped, so the final scroll position could be missed.

Throttle with a trailing call#

JavaScript
function throttle(fn, interval = 200) {
  let lastRun = 0;
  let timerId = null;
  let lastArgs;

  return function (...args) {
    lastArgs = args;
    const remaining = interval - (Date.now() - lastRun);

    if (remaining <= 0) {
      clearTimeout(timerId);
      timerId = null;
      lastRun = Date.now();
      fn.apply(this, lastArgs);
    } else if (!timerId) {
      timerId = setTimeout(() => {
        lastRun = Date.now();
        timerId = null;
        fn.apply(this, lastArgs);   // make sure the final event is handled
      }, remaining);
    }
  };
}

window.addEventListener("scroll", throttle(() => {
  progressBar.style.width = `${(scrollY / (document.body.scrollHeight - innerHeight)) * 100}%`;
}, 100));

Leading vs trailing edge#

Both techniques can fire on the leading edge (at the start of a burst), the trailing edge (at the end), or both.

JavaScript
function debounce(fn, delay, { leading = false } = {}) {
  let timerId;
  return function (...args) {
    const callNow = leading && !timerId;
    clearTimeout(timerId);
    timerId = setTimeout(() => {
      timerId = null;
      if (!leading) fn.apply(this, args);
    }, delay);
    if (callNow) fn.apply(this, args);
  };
}

// Leading debounce: stop double-submits on a button
submitBtn.addEventListener("click", debounce(submitForm, 1000, { leading: true }));

Adding cancel#

Real implementations let you cancel a pending call, for example when a component unmounts:

JavaScript
function debounce(fn, delay) {
  let timerId;
  const debounced = function (...args) {
    clearTimeout(timerId);
    timerId = setTimeout(() => fn.apply(this, args), delay);
  };
  debounced.cancel = () => clearTimeout(timerId);
  return debounced;
}

Using them in React#

A common bug is creating a new debounced function on every render, which resets the timer each time. Keep the debounced value in a hook instead:

JavaScript
import { useEffect, useState } from "react";

function useDebouncedValue(value, delay = 400) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const id = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(id);       // cleanup cancels the pending update
  }, [value, delay]);
  return debounced;
}

function SearchBox() {
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebouncedValue(query);

  useEffect(() => {
    if (debouncedQuery) fetchResults(debouncedQuery);
  }, [debouncedQuery]);

  return <input value={query} onChange={(e) => setQuery(e.target.value)} />;
}

Which one should I use?#

EventUseWhy
Search input / autocompleteDebounceOnly the final text matters
Window resize → recalculate layoutDebounceOnly the final size matters
Auto-save a draftDebounceSave when the user pauses
Scroll progress / sticky headerThrottleNeeds regular updates while scrolling
Infinite scroll "load more"ThrottleCheck position regularly
Mousemove / dragThrottle (or requestAnimationFrame)Smooth, steady updates
Button double-click protectionLeading debounceRun once, ignore repeats
Tip

For anything visual tied to animation frames, requestAnimationFrame is often better than a time-based throttle: it naturally runs at most once per frame. For infinite scroll, IntersectionObserver avoids scroll listeners entirely.

Debounce is not cancellation

Debouncing a search reduces requests, but responses can still arrive out of order. Pair it with AbortController to cancel stale requests. See Fetch API error handling and AbortController.

Debounce and throttle are classic examples of the decorator pattern from JavaScript design patterns. Forgetting to remove throttled listeners is also a common cause of memory leaks.

Key takeaways#

  • Debounce runs a function only after events stop for a set time; throttle runs it at most once per interval.
  • Both are higher-order functions built on closures and setTimeout.
  • Use debounce for search, resize and auto-save; throttle for scroll, drag and continuous input.
  • Leading and trailing options control whether the first or last call fires.
  • In React, debounce values in a hook with cleanup, and pair search debouncing with AbortController.