Skip to content

Instantly share code, notes, and snippets.

@jeremy-code
Created March 6, 2024 03:08
Show Gist options
  • Save jeremy-code/2c6f2d9d1910543d8e8f25aa15a1d51e to your computer and use it in GitHub Desktop.
Save jeremy-code/2c6f2d9d1910543d8e8f25aa15a1d51e to your computer and use it in GitHub Desktop.
debounce.ts
export function debounce<T extends (...args: Parameters<T>) => ReturnType<T>>(
callback: T,
wait: number,
immediate?: boolean
): (...args: Parameters<T>) => void {
let timeout: NodeJS.Timeout | undefined;
return function (this: ThisParameterType<T>, ...args: Parameters<T>): void {
const later = () => {
timeout = undefined;
if (!immediate) callback.apply(this, args);
};
const callNow = immediate && timeout === undefined;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) callback.apply(this, args);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment