@cc-heart/utils
Version:
🔧 javascript common tools collection
23 lines (21 loc) • 712 B
text/typescript
import { type fn } from '../typings/helper'
const weakMap = new WeakMap()
/**
* Returns a debounced version of the provided function that delays its
* execution until a certain amount of time has passed since the last time it was called.
* @param fn - The function to be debounced.
* @param delay - The number of milliseconds to wait before executing the function.
* @return - The debounced version of the provided function.
*/
export function useDebounce(fn: fn, delay = 500) {
return (...args: any) => {
if (weakMap.has(fn)) {
clearTimeout(weakMap.get(fn))
}
const timer = setTimeout(() => {
fn(...args)
weakMap.delete(fn)
}, delay)
weakMap.set(fn, timer)
}
}