Debounce vs Throttle in JavaScript

When handling user events like scrolling or typing, performance matters. Debounce and throttle are two patterns that prevent functions from running too often.

// Debounce: runs AFTER the user stops triggering the event
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

// Throttle: runs AT MOST once every interval
function throttle(fn, interval) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= interval) {
      fn(...args);
      last = now;
    }
  };
}

  • Debounce waits until no more events fire (great for search inputs).
  • Throttle ensures function runs at controlled intervals (great for scroll events).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *