Skip to content

Commit c9bf1b3

Browse files
committed
feat(core): debounce throttle tool
1 parent db89b88 commit c9bf1b3

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

packages/core/function/tools.ts

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 函数节流(每隔一段时间执行一次,防止函数过于频繁调用,导致性能问题)
3+
* @param {Function} fn
4+
* @param {number} wait 时间(单位:ms)
5+
* @returns 节流函数
6+
*/
7+
export const throttle = (fn: Function, wait: number = 300) => {
8+
let timer = false;
9+
return (...args: any[]) => {
10+
if (timer) return;
11+
timer = true;
12+
setTimeout(() => {
13+
fn(...args);
14+
timer = false;
15+
}, wait);
16+
};
17+
};
18+
/**
19+
* 函数防抖(保证一个函数在多少毫秒内不被再次触发,只会执行一次)
20+
* @param fn 将要处理的函数
21+
* @param wait 事件(单位:ms)
22+
* @param immediate 是否在触发事件后,在时间段n开始,立即执行;否则在时间段n结束,才执行。
23+
* @returns 防抖函数
24+
*/
25+
export const debounce = (fn: Function, wait: number, immediate: boolean = false) => {
26+
let timer: any = null;
27+
return (this: unknown, ...args: any) => {
28+
if (timer) {
29+
clearTimeout(timer);
30+
timer = null;
31+
}
32+
if (immediate) {
33+
if (!timer) fn.apply(this, args); // 第一次调用时执行
34+
timer = setTimeout(() => {
35+
// n秒内多次触发事件,重新计算timer
36+
timer = null; // n秒内没有触发事件,timer设置为null,保证n秒后能重新触发事件
37+
}, wait);
38+
} else {
39+
timer = setTimeout(() => {
40+
// 延迟指定毫秒后调用
41+
fn.apply(this, args);
42+
}, wait);
43+
}
44+
};
45+
};

0 commit comments

Comments
 (0)