javascript 简易版前端队列

161 阅读1分钟
// js简易版本队列
import { generateId } from './utils'; //生成随机数
class JsQueue {
  interval: number; // 当前处理最大阈值
  pathname: string;
  timer: any; //定时器实例
  INTERVAL: number; //轮训间隔/ms
  requestList: any[]; //请求列表
  push: any[];
  max: number;
  constructor(max = 10, interval = 1000) {
    this.max = max;
    this.pathname = '';
    this.interval = interval;
    this.requestList = [];
    this.timer = null;
    this.push = [];
    this.start();
  }
  add(req: any): string {
    if (window.location.pathname !== this.pathname) {
      this.pathname = window.location.pathname;
      this.clear();
    }
    const id = generateId();
    this.requestList.push({ req, id });
    return id;
  }
  start(): void {
    const evt: any = new Event('queue');
    this.timer = setInterval(() => {
      this.push = this.push.filter((e) => !e.state);

      if (this.requestList.length && this.push.length <= this.max) {
        // 每秒只处理9条
        this.push.push(...this.requestList.splice(0, this.max - this.push.length));
        this.push.forEach((d) => {
          d.state = 1;
          evt.data = d;
          //抛发事件
          document.dispatchEvent(evt);
        });
      }
    }, this.INTERVAL);
  }
  http(param: any): Promise<any> {
    const id = this.add(param);
    return new Promise((resolve, reject) => {
      const handler = async (e: any) => {
        if (e.data.id === id) {
          const { http, body } = e.data.req;
          resolve(await http(...body));
        }
      };
      document.addEventListener('queue', handler);
    });
  }
  stop(): void {
    clearInterval(this.timer);
    this.timer = null;
  }
  clear(): void {
    this.requestList = [];
    this.timer = null;
    this.push = [];
    this.stop();
  }
}

export { JsQueue };