More JavaScript answers

by Danny
Published 2 min read

Debounce waits until events stop before running a function; throttle runs it at most once per interval. Learn when to use each, with a small implementation of both.

The short answer

#

Both limit how often a function runs when an event fires many times. Debounce waits until the events have stopped for a set time, then runs once. Throttle runs at most once per interval while the events keep coming. Use debounce for search boxes and resize handlers that only need the final value; use throttle for scroll or pointer tracking that needs steady updates.


_10
searchInput.addEventListener('input', debounce(runSearch, 300));
_10
window.addEventListener('scroll', throttle(updateProgressBar, 100));

Why it happens

#

Events such as input, scroll, resize and pointermove can fire dozens of times a second. If each one triggers a network request or a layout calculation, the page slows down or the server gets flooded.

The two techniques solve slightly different problems:

  • Debounce cares about the end of a burst. Typing "react" fires five input events, but you only want to search once the user pauses.
  • Throttle cares about a steady rate. While the user scrolls for three seconds, you want regular updates, not one at the end.

How to fix it

#

A small debounce

Each call clears the previous timer and starts a new one, so the function only runs once the calls stop for wait milliseconds.


_13
function debounce(fn, wait) {
_13
let timer;
_13
return function (...args) {
_13
clearTimeout(timer);
_13
timer = setTimeout(() => fn.apply(this, args), wait);
_13
};
_13
}
_13
_13
const onInput = debounce((event) => {
_13
fetchResults(event.target.value);
_13
}, 300);
_13
_13
searchInput.addEventListener('input', onInput);

A small throttle

This version runs straight away on the first call, ignores calls during the interval, and runs once more at the end with the latest arguments so the final position is not lost.


_28
function throttle(fn, interval) {
_28
let last = 0;
_28
let timer;
_28
let lastArgs;
_28
_28
return function (...args) {
_28
const now = Date.now();
_28
const remaining = interval - (now - last);
_28
lastArgs = args;
_28
_28
if (remaining <= 0) {
_28
clearTimeout(timer);
_28
timer = undefined;
_28
last = now;
_28
fn.apply(this, args);
_28
} else if (!timer) {
_28
timer = setTimeout(() => {
_28
last = Date.now();
_28
timer = undefined;
_28
fn.apply(this, lastArgs);
_28
}, remaining);
_28
}
_28
};
_28
}
_28
_28
window.addEventListener('scroll', throttle(() => {
_28
progress.style.width = `${getScrollPercent()}%`;
_28
}, 100));

Throttle visual updates with requestAnimationFrame

If the work only updates the screen, tie it to the browser's paint cycle instead of a fixed interval. It runs at most once per frame.


_10
let scheduled = false;
_10
_10
window.addEventListener('scroll', () => {
_10
if (scheduled) return;
_10
scheduled = true;
_10
requestAnimationFrame(() => {
_10
scheduled = false;
_10
updateStickyHeader();
_10
});
_10
});

Choosing between them

  • Search as you type, autosave, form validation: debounce.
  • Window resize where you only need the final size: debounce.
  • Scroll position, infinite scroll checks, drag handling: throttle.
  • Animations or anything purely visual: requestAnimationFrame.

Common pitfalls

#
  • Creating a new debounced function on every event or render. Each one has its own timer, so nothing is debounced. Create it once and reuse it.
  • Losing this by using an arrow function for the returned wrapper when you need the element. The examples use a regular function for that reason.
  • Debouncing scroll handlers that should update continuously. The UI only changes after scrolling stops.
  • Forgetting to cancel pending timers when a component unmounts. Add a cancel method that calls clearTimeout if you need one.
  • Using throttle to save network requests while typing. The user still sends partial queries; debounce is usually better there.
#

Was this resource helpful?