d
Amit DhamuSoftware Engineer
 

Debounce

2 minute read 00000 views

When you want to implement a delay when invoking a function, leveraging a debounce function can help.

A good example would be using it for something like a live search input where you might be hitting an API to retrieve some search results. Constantly hitting the API on each keystroke could be wasteful.

Function

const debounce = <T extends (...args: any[]) => ReturnType<T>>(
  callback: T,
  timeout: number
): ((...args: Parameters<T>) => void) => {
  let timer: ReturnType<typeof setTimeout>

  return (...args: Parameters<T>) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      callback(...args)
    }, timeout)
  }
}

Usage

const myDebouncedFunction = debounce(e => {
  console.log(e)
}, 3000)

myDebouncedFunction('Hello world')

// Console logs 'Hello world' after 3 seconds

Multiple Arguments

const myDebouncedFunction = debounce((name: string, location: string) => {
  console.log(`My name is ${name} and I am in ${location}`)
}, 3000)

myDebouncedFunction('Amit', 'the UK')

// Console logs 'My name is Amit and I am in the UK' after 3 seconds

Alternative Usage (Inline)

const greeting = (name: string, location: string) => {
  console.log(`My name is ${name} and I am in ${location}`)
}

debounce(greeting, 3000)('Amit', 'the UK')

// Console logs 'My name is Amit and I am in the UK' after 3 seconds