Skip to content

Instantly share code, notes, and snippets.

@cristoferespindola
Created February 14, 2024 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristoferespindola/d469891e580049fe34a5ac214f1503ec to your computer and use it in GitHub Desktop.
Save cristoferespindola/d469891e580049fe34a5ac214f1503ec to your computer and use it in GitHub Desktop.
useDebouncedFunction
import { useRef } from 'react'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Func = (...args: any[]) => any
type DebouncedFunction<F extends Func> = (...args: Parameters<F>) => Promise<undefined | ReturnType<F>>
export function useDebouncedFunction<F extends Func>(
func: F | undefined,
milliseconds: number
): DebouncedFunction<F> | undefined {
const timeoutIdRef = useRef<number | undefined>()
if (!func) {
return undefined
}
const debounced: DebouncedFunction<F> = (...args: Parameters<F>) => {
return new Promise((resolve) => {
if (timeoutIdRef.current !== undefined) {
clearTimeout(timeoutIdRef.current)
}
timeoutIdRef.current = window.setTimeout(() => {
resolve(func(...args))
timeoutIdRef.current = undefined
}, milliseconds)
})
}
return debounced
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment