-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebounce.ts
More file actions
27 lines (23 loc) · 859 Bytes
/
debounce.ts
File metadata and controls
27 lines (23 loc) · 859 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { TAnyFunction } from '../typeHelpers'
/**
* ### debounce(func, wait)
*
* Create a debounced function that delays invoking `func` until `wait` milliseconds
* have elapsed since the last time the debounced function was invoked.
*
* ```js
* const func = () => console.log('Heavy processing happening')
* const debouncedFunc = flocky.debounce(func, 250)
* ```
*/
type FunctionWithVoidReturn<TFunc extends TAnyFunction<void>> = (...args: Parameters<TFunc>) => void
export function debounce<TFunc extends TAnyFunction<void>>(
func: TFunc,
wait: number
): FunctionWithVoidReturn<TFunc> {
let timeoutID: NodeJS.Timeout | null = null
return function (this: unknown, ...args: Array<unknown>) {
if (timeoutID) clearTimeout(timeoutID)
timeoutID = setTimeout(() => func.apply(this, args), wait)
} as FunctionWithVoidReturn<TFunc>
}