Hiprup

What is debouncing and throttling?

Both limit how often a function runs in response to rapid events like typing, scrolling, or resizing.

  • Debounce — waits until activity stops, then runs once. Good for search-as-you-type or validating after the user pauses.

  • Throttle — runs at most once per time interval, however many events fire. Good for scroll or resize handlers.

One-line difference: debounce waits for a pause; throttle runs on a fixed schedule.

// Debounce implementation
function debounce(fn, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// Usage: search after user stops typing for 300ms
const search = debounce((query) => {
  fetch(`/api/search?q=${query}`).then(r => r.json());
}, 300);

input.addEventListener('input', (e) => search(e.target.value));

// Throttle implementation
function throttle(fn, interval) {
  let lastTime = 0;
  return function(...args) {
    const now = Date.now();
    if (now - lastTime >= interval) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
}

// Usage: update scroll position at most every 100ms
const onScroll = throttle(() => {
  console.log('Scroll position:', window.scrollY);
}, 100);

window.addEventListener('scroll', onScroll);

Debounce: each call resets the timer (clearTimeout + setTimeout). The function only fires after the user pauses for the full delay. Throttle: checks if enough time has passed since the last call.

If yes, executes immediately. If no, the call is dropped. Debounce = wait for pause, Throttle = limit rate.

Implement both from scratch — this is a very common coding question. Key difference: debounce waits for inactivity (search), throttle limits rate (scroll).

Show practical use cases for each. Know that lodash provides _.debounce and _.throttle.

What is debouncing and throttling? | Hiprup