鸿蒙中的防抖功能及封装实现
/ 执行完毕后重置 timeoutId。// 如果已经有定时器存在,清除它。// 设置新的定时器。
·
export class Debouncer {
private timeoutId: number | null = null;
private delay: number;
constructor(delay: number) {
this.delay = delay;
}
// 防抖函数
debounce(callback: () => void): void {
// 如果已经有定时器存在,清除它
if (this.timeoutId !== null) {
clearTimeout(this.timeoutId);
}
// 设置新的定时器
this.timeoutId = setTimeout(() => {
callback();
this.timeoutId = null; // 执行完毕后重置 timeoutId
}, this.delay);
}
// 取消防抖
cancel(): void {
if (this.timeoutId !== null) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
}
}更多推荐


所有评论(0)