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;
    }
  }
}
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐