export class WaitingQueue {
constructor(waitingTime = 1) {
this.isBusy = false;
this.isFirst = true;
this.waitingTime = waitingTime;
this.box = [];
}
init() {
this.isBusy = false;
this.isFirst = true;
this.box = [];
}
get size() {
return this.box.length;
}
get isEmpty() {
return !this.box.length;
}
clear() {
this.init();
}
lazyRun(func, time = 0) {
setTimeout(func.bind(this), time);
}
entry(func) {
this.box.unshift(func);
if (this.isFirst) {
this.isFirst = false;
this.next();
return;
}
}
next() {
if (!this.check()) {
return;
}
let func = this.box.pop();
func(
(time) =>
new Promise((resolve) => {
this.isBusy = false;
let waitTime = (time ?? this.waitingTime) * 1000;
this.lazyRun(() => {
this.lazyRun(this.next);
resolve();
}, waitTime);
})
);
}
check() {
if (this.isEmpty) {
this.isFirst = true;
this.isBusy = false;
return false;
}
if (this.isBusy) {
return false;
}
this.isBusy = true;
return true;
}
}
使用方法:
let waitQue = new WaitingQueue(0.5);
waitQue.entry((done) => {
done(5).then(() => {
console.log('haha')
});
});