Docs
/
Cohort 2
/
Week 4
/
Debouncing and Throttling

Debouncing and Throttling

Debouncing

Debouncing is a technique to limit the rate at which a function can fire. When you debounce a function, you prevent it from being called multiple times.

function debounce(func, delay) {
  let timeoutId;
  return function (...args) {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
      func.apply(null, args);
    }, delay);
  };
}

Throttling

Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval.

function throttle(func, limit) {
  let inThrottle;
  return function (...args) {
    if (!inThrottle) {
      func.apply(null, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}
Last updated on February 12, 2024