【关键字】
onClick事件 / 重复点击 / throttle
【问题描述】
组件中onClick事件怎么禁止短时间内重复点击。
【解决方案】
定义一个节流函数throttle,设置间隔时间控制事件的触发。
参考代码如下:
function throttle(func: Function, interval: number) {
let lastTime = 0;
return () => {
const nowTime = Date.now();
const remainTime = interval - (nowTime - lastTime);
if (remainTime <= 0) {
lastTime = nowTime;
func();
}
};
}
@Entry
@Component
struct Index {
@State num: number = 0
build() {
Row() {
Column() {
Text(this.num.toString())
Button("click").onClick(throttle(() => {
this.num++
}, 5000))
}
.width('100%')
}
.height('100%')
}
}