TechnicalMedium JavaScript

What is the difference between debouncing and throttling?

Asked for Frontend Developer, Full-Stack Developer

Why they ask this: Common in search boxes, scroll and resize handlers; shows you think about performance.

Answer

Both limit how often a function runs:

  • Debounce: run the function only after events stop for a given time. Typical use: a search box that calls the API 300 ms after the user stops typing.
  • Throttle: run the function at most once per interval while events keep firing. Typical use: a scroll handler that runs every 200 ms.
js
function debounce(fn, delay = 300) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

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

Can you explain this in your own words?

Back to question bank