-
Notifications
You must be signed in to change notification settings - Fork 0
/
throttle.ts
54 lines (51 loc) · 1.31 KB
/
throttle.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
/**
* @packageDocumentation
* @module @tomato-js/function
*/
import { FunctionType, isNil } from "@tomato-js/shared";
type Options = {
isImmediate: boolean;
};
/**
* 函数节流
*
* 新增于v0.0.17
*
* 脚本举例
* ```
* import { throttle } from '@tomato-js/function'
* throttle(() => console.log('throttle'), 1000, { isImmediate: true });
* ```
*
* @param func - 调用函数
* @param wait - 延迟执行毫秒数
* @param isImmediate - 是否立即执行,true 表立即执行,false 表非立即执行
* @returns 新函数
*/
export function throttle<F extends FunctionType>(
func: F,
wait: number = 50,
options: Options = {
isImmediate: false
}
): (this: ThisParameterType<F>, ...args: Parameters<F>) => void {
let timeout: ReturnType<typeof setTimeout> | undefined;
return function(this: ThisParameterType<F>, ...args: Parameters<F>) {
const context = this;
const doLater = function() {
if (!isNil(timeout)) {
clearTimeout(timeout);
}
timeout = undefined;
if (!options.isImmediate) {
func.apply(context, args);
}
};
if (!isNil(timeout)) return;
const shouldCallNow = options.isImmediate && isNil(timeout);
timeout = setTimeout(doLater, wait);
if (shouldCallNow) {
func.apply(context, args);
}
};
}