Skip to content

Instantly share code, notes, and snippets.

@ca0v
Last active April 10, 2025 21:15
Show Gist options
  • Save ca0v/73a31f57b397606c9813472f7493a940 to your computer and use it in GitHub Desktop.
Save ca0v/73a31f57b397606c9813472f7493a940 to your computer and use it in GitHub Desktop.
Typescript Debounce
// ts 3.6x
function debounce<T extends Function>(cb: T, wait = 20) {
let h = 0;
let callable = (...args: any) => {
clearTimeout(h);
h = setTimeout(() => cb(...args), wait);
};
return <T>(<any>callable);
}
// usage
let f = debounce((a: string, b: number, c?: number) => console.log(a.length + b + c || 0));
f("hi", 1, 1);
f("world", 1);
@sylvainpolletvillard
Copy link

Sure, ignoring the error works to fix the error

@humayunkabir
Copy link

 debounce = <F extends (...args: Parameters<F>) => ReturnType<F>>(
  func: F,
  waitFor: number,
) => {
  let timeout: NodeJS.Timeout

  const debounced = (...args: Parameters<F>) => {
    clearTimeout(timeout)
    timeout = setTimeout(() => func(...args), waitFor)
  }

  return debounced
}

The timeout type should be ReturnType<typeof setTimeout>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment