Import {generateId} from './utils'; // Generate random number class JsQueue {interval: number; // Current maximum threshold pathName: string; timer: any; // Timer instance INTERVAL: number; // ms requestList: any[]; // Request list 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) {// Only 9 entries per second 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 };Copy the code