UNPKG

@cc-heart/utils

Version:

🔧 javascript common tools collection

23 lines (21 loc) • 744 B
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. */ function useDebounce(fn, delay = 500) { return (...args) => { if (weakMap.has(fn)) { clearTimeout(weakMap.get(fn)); } const timer = setTimeout(() => { fn(...args); weakMap.delete(fn); }, delay); weakMap.set(fn, timer); }; } export { useDebounce };