Skip to main content

Throttle Function

Performance3 functions

Utility Overview

Details

Limits function execution to at most once per specified time period, ensuring regular execution during continuous events

Category:Performance
Functions:throttle, throttleAdvanced, throttleImmediate
Concepts:
closureshigher-order functionsrate limitingperformance

Implementation

throttle

Time: O(1) | Space: O(1)
export function throttle<T extends ThrottlableFunction>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  if (typeof func !== 'function') throw new Error("First argument must be a function");
  if (!Number.isInteger(wait) || wait < 0) throw new Error("Wait time must be a non-negative integer");
  
  let lastCall = 0;

  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= wait) {
      lastCall = now;
      func(...args);
    }
  };
}

// Alternative implementation with leading and trailing options

Usage Examples

Scroll event optimization

const throttledScroll = throttle(handleScroll, 100);
window.addEventListener('scroll', throttledScroll);

// handleScroll executes maximum once per 100ms during scrolling

Button click protection

const throttledSubmit = throttle(submitForm, 250);
button.addEventListener('click', throttledSubmit);

// Prevents rapid-fire clicks, allows max 4 submissions per second

Advanced throttle with options

const throttledResize = throttleAdvanced(updateLayout, 500, {
  leading: true,
  trailing: false
});
window.addEventListener('resize', throttledResize);

// Executes immediately, then ignores calls for 500ms

API request rate limiting

const throttledApi = throttleImmediate(fetchData, 1000);
searchInput.addEventListener('input', () => throttledApi(query));

// API calls limited to once per second maximum