Difference between debounce and throttle

Debounce and throttle are both techniques used to control the frequency of function calls. However, they serve different purposes and have distinct characteristics.

Debounce

Debounce is a technique that delays executing a function until a certain period of inactivity has passed.

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

// Usage
const handleInput = debounce((event) => {
  console.log("Fetching suggestions for:", event.target.value);
}, 300);

document.querySelector("input").addEventListener("input", handleInput);

Throttle

Throttle is a technique that limits a function to run at most once every interval no matter how many times the event occurs.

function throttle(fn, limit) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= limit) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

// Usage
const handleScroll = throttle(() => {
  console.log("Scroll position updated");
}, 300);

window.addEventListener("scroll", handleScroll);

javascript