throttle

See debounce if you want your function to run at the end of the N seconds.

typescriptjavascript
const throttle = <T extends CallableFunction>(fn: T, delay: number): T => {
  let canRun = true
 
  return ((...args: any[]) => {
    if (canRun) {
      fn(...args)
      canRun = false
      setTimeout(() => {
        canRun = true
      }, delay)
    }
  }) as any
}
const throttle = (fn, delay) => {
  let canRun = true
 
  return (...args) => {
    if (canRun) {
      fn(...args)
      canRun = false
      setTimeout(() => {
        canRun = true
      }, 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