js 延迟执行任务

// 延迟执行任务
class DelayTasks {
  #tasks = [];
  #proxyTasks = [];
  #tasksSum = 0;
  #tasksStatus = false;
  #duration = 1000;
  constructor(duration = 1000) {
    // 初始化任务队列数组
    this.#tasks = [];
    // 重置任务队列运行状态
    this.#tasksStatus = false;
    // 重置任务计数器
    this.#tasksSum = 0;
    // 设置任务执行间隔时间
    this.#duration = duration;

    // 创建代理对象监听任务队列变化
    this.#proxyTasks = new Proxy(this.#tasks, {
      // 属性设置拦截器
      set: (target, key, value) => {
        target[key] = value;
        // 当队列有任务且未运行时,启动任务执行
        if (!!target?.length && !this.#tasksStatus) {
          this.#runTasks();
        }
        return true;
      },
      // 属性获取拦截器
      get: (target, key) => {
        return target[key];
      },
    });
  }

  /**
   * 添加延迟任务到队列
   * @param {Function} task - 要执行的任务函数
   */
  addTask(task) {
    // 将任务包装为 Promise 推入代理队列
    this.#proxyTasks.push(() => {
      return new Promise((resolve, reject) => {
        // 设置延迟执行
        setTimeout(async () => {
          try {
            // 执行任务函数并传递当前任务序号
            typeof task === "function" && (await task(this.#tasksSum));
          } catch (e) {
            reject(e);
          }
          // 完成任务后更新计数器
          resolve(this.#tasksSum);
          console.log("任务:" + this.#tasksSum);
          this.#tasksSum++;
        }, this.#duration);
      });
    });
  }
  async #runTasks() {
    this.#tasksStatus = true;
    while (!!this.#proxyTasks.length) {
      const task = this.#proxyTasks.shift();
      try {
        task && (await task());
      } catch (error) {
        console.log("任务队列执行错误", error);
      }
    }
    this.#tasksStatus = false;
  }
}