Files
QXTstore/QXTfront/uni_modules/lime-shared/throttle/index.ts

89 lines
2.5 KiB
TypeScript
Raw Normal View History

2025-11-05 17:34:23 +08:00
// @ts-nocheck
/**
*
* @param fn
* @param interval
* @returns
*/
export type ThrottleOptions = {
/**
*
* @default true
*/
leading ?: boolean;
/**
*
* @default true
*/
trailing ?: boolean;
}
/**
*
* @param func
* @param wait
* @param options
* @param options.leading true
* @param options.trailing true
* @returns
*/
// #ifndef APP-ANDROID
export function throttle<T extends (...args : any[]) => any>(
func : T,
wait : number,
options : ThrottleOptions = {}
) : (...args : Parameters<T>) => void {
let lastCallTime = 0;
let timerId : ReturnType<typeof setTimeout> | null = null;
const { leading = true, trailing = true } = options;
return function (...args : Parameters<T>) {
const now = Date.now();
const timeSinceLastCall = now - lastCallTime;
// 1. 如果 leading=true 且距离上次调用超过 wait立即执行
if (leading && timeSinceLastCall >= wait) {
lastCallTime = now;
func.apply(this, args);
}
// 2. 如果 trailing=true设置定时器在 wait 时间后执行最后一次调用
else if (trailing && !timerId) {
timerId = setTimeout(() => {
lastCallTime = Date.now();
func.apply(this, args);
timerId = null;
}, wait - timeSinceLastCall);
}
};
}
// #endif
// #ifdef APP-ANDROID
export function throttle<T extends any|null>(
func: (args : T) => void,
wait : number,
options : ThrottleOptions = {}
) : (args : T) => void {
let lastCallTime = 0;
let timerId = -1;
const { leading = true, trailing = true } = options;
return function (args : T) {
const now = Date.now();
const timeSinceLastCall = now - lastCallTime;
// 1. 如果 leading=true 且距离上次调用超过 wait立即执行
if (leading && timeSinceLastCall >= wait) {
lastCallTime = now;
func(args);
}
// 2. 如果 trailing=true设置定时器在 wait 时间后执行最后一次调用
else if (trailing && timerId > -1) {
timerId = setTimeout(() => {
lastCallTime = Date.now();
func(args);
timerId = -1;
}, wait - timeSinceLastCall);
}
};
}
// #endif