-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
62 lines (51 loc) · 1.33 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
* @Author: Rainy
* @Date: 2020-01-02 18:31:50
* @LastEditors : Rainy
* @LastEditTime : 2020-01-02 19:58:10
*/
import { WithParamsReturnAnyFunction, ObjectMap } from 'types';
import { isAbsType } from 'utils/type';
export function _throttle(
callback: WithParamsReturnAnyFunction,
wait: number = 300,
options: ObjectMap<any> = {},
): WithParamsReturnAnyFunction {
let last: number = 0;
let timer: any = null;
let result: any = null;
if (!isAbsType(options)) {
throw new Error('options must be object');
}
const { leading = false, trailing = false, ...option } = options;
const throttle = () => {
let params: any = arguments
let now = +new Date();
if (leading) {
timer = setTimeout(() => {
timer = null;
}, wait);
// @ts-ignore
result = !timer && callback && callback.apply(this, params);
} else {
if (last && now < last + wait) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
// @ts-ignore
result = callback && callback.apply(this, params)
}, wait);
} else {
last = now;
// @ts-ignore
result = callback && callback.apply(this, params)
}
}
return result;
}
throttle.cancel = () => {
clearTimeout(timer);
timer = null;
}
return throttle;
}