-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
46 lines (45 loc) · 1.12 KB
/
index.ts
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { createFilterWrapper, throttleFilter } from "../utils"
import type { FunctionArgs, PromisifyFn } from "../utils"
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param fn - A function to be executed after delay seconds debounced.
*
* @param s - The time to wait before invoking the function in seconds
*
* @param trailing - If true, call fn again after the time is up
*
* @param leading - if true, call fn on the leading edge of the s timeout
*
* @param rejectOnCancel - Whether to reject the promise if the function is cancelled.
*
* @example
* ```ts
* const fn = throttle(() => console.log("Hello World"), 1)
*
* fn() // "Hello World"
*
* fn() // Nothing
*
* await sleep(1)
*
* fn() // "Hello World"
*
* fn() // Nothing
* ```
*
* @returns A new throttled function.
*/
export function throttle<T extends FunctionArgs>(
fn: T,
s = 0.2,
trailing = false,
leading = true,
rejectOnCancel = false
): PromisifyFn<T> {
return createFilterWrapper(
throttleFilter(s, trailing, leading, rejectOnCancel),
fn
)
}