debounce

See throttle if you want your function to run at the start of the N seconds.

typescriptjavascript
const debounce = <T extends CallableFunction>(fn: T, delay: number): T => {
  let timer: ReturnType<typeof setTimeout>
 
  return ((...args: any[]) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }) as any
}
const debounce = (fn, delay) => {
  let timer
 
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn(...args)
    }, delay)
  }
}
Created 28/03/21Updated 28/03/21
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here