import { generateId } from './utils';
class JsQueue {
interval: number;
pathname: string;
timer: any;
INTERVAL: number;
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) {
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 };