Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

debounce typescript

const debounce = <F extends (...args: any[]) => any>(
  func: F,
  waitFor: number
) => {
  let timeout: ReturnType<typeof setTimeout> | null = null

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

  return debounced as (...args: Parameters<F>) => ReturnType<F>
}

// Usage
const debounceCallback = () => {
  console.log('Debounce')
}

debounce<typeof debounceCallback>(debounceCallback, 500)
 
PREVIOUS NEXT
Tagged: #debounce #typescript
ADD COMMENT
Topic
Name
4+2 =