← Back to Snippets
typescript

Throttle Function

Limit function execution to at most once per time period

utility performance events

Throttle ensures a function runs at most once per specified interval. Unlike debounce, it guarantees regular execution during continuous calls.

function throttle<T extends (...args: any[]) => any>(
  fn: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle = false;

  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      fn(...args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

Usage

// Scroll handler - fires at most every 100ms
const handleScroll = throttle(() => {
  console.log('Scroll position:', window.scrollY);
}, 100);

window.addEventListener('scroll', handleScroll);

Debounce vs Throttle

ScenarioUse
Search inputDebounce
Scroll positionThrottle
Window resizeThrottle
Form validationDebounce
Game loopThrottle