HarmonyOS 鸿蒙Next中节流、防抖
HarmonyOS 鸿蒙Next中节流、防抖
class Util {
private static instance:Util | undefined;
private constructor() {
}
public static getInstance() {
if (!Util.instance) {
Util.instance = new Util();
}
return Util.instance;
}
// 防抖 在一段时间内函数被多次触发,防抖让函数在一段时间后最终只执行一次
debounce(func: (event: ClickEvent) => void, delay?: number) {
let timer: number;
return (event: ClickEvent) => {
clearTimeout(timer);
timer = setTimeout(() => {
func(event);
}, delay ? delay : 1000);
};
}
// 节流 在规定的时间内,只执行一次
throttle(func: (event: ClickEvent) => void, delay?: number) {
let inThrottle: boolean;
return (event: ClickEvent) => {
if (!inThrottle) {
func(event);
inThrottle = true;
setTimeout(() => inThrottle = false, delay ? delay : 1000);
}
};
}
}
@Entry
@Component
struct Page {
@State num:number = 0
@State num2:number = 0
click = Util.getInstance().debounce((event: ClickEvent) => {
this.num++;
});
click2 = Util.getInstance().throttle((event: ClickEvent) => {
this.num2++;
});
build() {
Column() {
Text(`防抖${this.num}`)
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.onClick((event) => {
this.click(event)
})
Text(`节流${this.num2}`)
.fontSize($r('app.float.page_text_font_size'))
.fontWeight(FontWeight.Bold)
.onClick((event) => {
this.click2(event)
})
}
.height('100%')
.width('100%')
}
}
更多关于HarmonyOS 鸿蒙Next中节流、防抖的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在HarmonyOS鸿蒙Next中,节流和防抖通过@ohos.util模块实现。节流使用Throttle类限制函数执行频率,防抖使用Debounce类延迟执行直到操作停止。两者均支持配置时间间隔和上下文绑定,适用于事件处理优化,提升应用性能。
更多关于HarmonyOS 鸿蒙Next中节流、防抖的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html