防抖与节流
// 输入框防抖方法
export const Debounce = (
fn: (...args: any[]) => void,
wait: number | undefined,
) => {
let timeout: NodeJS.Timeout | null = null;
return function (input: { persist: () => void }) {
input.persist();
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn, wait, input);
};
};
// 函数防抖
export const fnDebounce = (
fn: (...args: any[]) => void,
wait: number | undefined,
) => {
let timeout: NodeJS.Timeout | null = null;
return function () {
if (timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn, wait);
};
};
// 节流
export const throttle = (fn: Function, rateTime: number) => {
let timer: any = null;
return (...args: any[]) => {
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, rateTime);
}
};
};
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
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
编辑 (opens new window)
上次更新: 2022/06/17