HarmonyOS鸿蒙Next中ArkTS里怎么实现防抖与截流?
HarmonyOS鸿蒙Next中ArkTS里怎么实现防抖与截流?
6 回复
通过systemDateTime获取时间戳判断触发间隔:
import { systemDateTime } from '@kit.BasicServicesKit';
export namespace click {
let lastClickTime: number = 0;
export const onClick = (fun: () => void, jitterTime: number = 500) => {
return () => {
const currentTime = systemDateTime.getTime();
if (currentTime - lastClickTime < jitterTime) return;
lastClickTime = currentTime;
fun();
}
}
}
或者 工具类封装
export class ClickUtil {
private static throttleTimeoutID: number | null = null;
private static flag: boolean = false;
// 防抖
static debounce(func: () => void, delay: number = 500) {
if (ClickUtil.throttleTimeoutID !== null) {
clearTimeout(ClickUtil.throttleTimeoutID);
}
ClickUtil.throttleTimeoutID = setTimeout(() => {
func();
ClickUtil.throttleTimeoutID = null;
}, delay);
}
// 节流
static throttle(func: () => void, wait: number = 1000) {
if (!ClickUtil.flag) {
ClickUtil.flag = true;
func();
setTimeout(() => {
ClickUtil.flag = false;
}, wait);
}
}
}
更多关于HarmonyOS鸿蒙Next中ArkTS里怎么实现防抖与截流?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
楼主看一下这两个示例对你有没有帮助:根据具体的场景来使用
// ========== 防抖函数 ==========
debounceSearch: (text: string) => void = (() => {
let timer: number | undefined
return (text: string) => {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
console.info('防抖触发搜索:', text)
}, 500)
}
})();
// ========== 截流函数 ==========
throttleClick: () => void = (() => {
let lastTime = 0
return () => {
const now = Date.now()
if (now - lastTime >= 1000) {
lastTime = now
this.clickCount += 1
console.info('截流触发点击,次数:', this.clickCount)
}
}
})();
OpenHarmony三方库中心仓 这个三方库里面有方法
在HarmonyOS Next的ArkTS中实现防抖与节流:
防抖实现:
使用setTimeout
和clearTimeout
控制触发频率:
private timeoutId: number = 0;
debounce(func: () => void, delay: number) {
clearTimeout(this.timeoutId);
this.timeoutId = setTimeout(() => {
func();
}, delay);
}
节流实现: 通过时间戳判断执行间隔:
private lastExecTime: number = 0;
throttle(func: () => void, interval: number) {
let now = Date.now();
if (now - this.lastExecTime >= interval) {
func();
this.lastExecTime = now;
}
}