jiangwei小站
185 字
1 分钟
自用防抖
2024-01-02

Debounce.ts

class DebounceSingleton {
  private static instance: DebounceSingleton;
  private delay: number;
  private flag: boolean = true;
  private timer: number | null = null;

  private constructor() {}

  public static getInstance(): DebounceSingleton {
    if (!DebounceSingleton.instance) {
      DebounceSingleton.instance = new DebounceSingleton();
    }
    return DebounceSingleton.instance;
  }

  // 点的第一次
  public debounceFirst(callback: () => void, delay: number = 200): void {
    this.delay = delay;
    if (this.flag) {
      this.flag = false;
      callback();
    }
    setTimeout(() => {
      this.flag = true;
    }, this.delay);
  }

  // 点的最后一次
  public debounceFinally(callback: () => void, delay: number = 200): void {
    this.delay = delay;
    if (this.timer) {
      clearTimeout(this.timer);
    }
    this.timer = setTimeout(callback, this.delay);
  }

  // 接口返回后才行
  public async debounceResolve(
    callback: (flag: boolean) => void
  ): Promise<void> {
    if (this.flag) {
      this.flag = false;
      await callback(this.flag);
      this.flag = true;
    }
  }
}

export const Debounce = DebounceSingleton.getInstance();

使用方法

Debounce.debounceFirst(() => {})
Debounce.debounceFinally(() => {})
//最后一个后面再设计下
Debounce.debounceResolve(() => {
  return new Promise<void>((resolve, _reject) => {
    setTimeout(() => {
      resolve();
    }, 1000);
  });
});