Categories

Async2Utility1

Debounce

Useful for preventing functions from being called too frequently.

Contributed by @thanhhoan-v2

tsx
/**
 * Creates a debounced function that delays invoking the provided function
 * until after `wait` milliseconds have elapsed since the last time it was invoked.
 * @param func The function to debounce
 * @param wait The number of milliseconds to delay
 * @returns A debounced version of the original function
 */
function debounce<T extends (...args: unknown[]) => unknown>(
  func: T,
  wait: number,
): (...args: Parameters<T>) => void {
  let timeout: ReturnType<typeof setTimeout> | null = null;
 
  return function (...args: Parameters<T>): void {
    const later = () => {
      timeout = null;
      func(...args);
    };
 
    if (timeout !== null) {
      clearTimeout(timeout);
    }
 
    timeout = setTimeout(later, wait);
  };
}
GitHubEdit on GitHub