iota-utools 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/rollup.config.js +1 -1
- package/src/utools/debounce.ts +19 -0
- package/src/utools/index.ts +2 -0
- package/src/utools/throttle.ts +29 -0
package/package.json
CHANGED
package/rollup.config.js
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @description: 防抖函数
|
|
3
|
+
* @param {func} 需要防抖的函数
|
|
4
|
+
* @param {wait} 防抖时间
|
|
5
|
+
* @return {*} (context,...args):void
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export function debounce<T extends (...args: any[]) => void>(func: T, wait: number): (...args: Parameters<T>) => void {
|
|
9
|
+
let timeout: NodeJS.Timeout;
|
|
10
|
+
|
|
11
|
+
return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
|
|
12
|
+
const context = this; // 保存当前的 this 上下文
|
|
13
|
+
|
|
14
|
+
clearTimeout(timeout);
|
|
15
|
+
timeout = setTimeout(() => {
|
|
16
|
+
func.apply(context, args); // 使用 apply 绑定 this 和传递参数
|
|
17
|
+
}, wait);
|
|
18
|
+
};
|
|
19
|
+
}
|
package/src/utools/index.ts
CHANGED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @description: 节流函数
|
|
3
|
+
* @param {func} 需要节流的函数
|
|
4
|
+
* @param {wait} 节流时间区
|
|
5
|
+
* @return {*} (context,...args):void
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export function throttle<T extends (...args: any[]) => void>(func: T, limit: number): (...args: Parameters<T>) => void {
|
|
9
|
+
let lastFunc: NodeJS.Timeout;
|
|
10
|
+
let lastRan: number;
|
|
11
|
+
|
|
12
|
+
return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
|
|
13
|
+
const now = Date.now();
|
|
14
|
+
const context = this; // 保存当前的 this 上下文
|
|
15
|
+
|
|
16
|
+
if (!lastRan) {
|
|
17
|
+
func.apply(context, args);
|
|
18
|
+
lastRan = now;
|
|
19
|
+
} else {
|
|
20
|
+
clearTimeout(lastFunc);
|
|
21
|
+
lastFunc = setTimeout(() => {
|
|
22
|
+
if (now - lastRan >= limit) {
|
|
23
|
+
func.apply(context, args);
|
|
24
|
+
lastRan = now;
|
|
25
|
+
}
|
|
26
|
+
}, limit - (now - lastRan));
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
}
|