class Quene {
constructor(ms) {
this.quene = [];
this.interval = ms;
this.timer = null;
}
enquene(cb) {
this.quene.push(cb);
this.consume();
}
consumeItem() {
const cb = this.quene.shift();
cb();
if (!this.quene.length) {
clearInterval(this.timer);
this.timer = null;
}
}
consume() {
if (!this.timer) {
this.timer = setInterval(this.consumeItem.bind(this), this.interval);
}
}
}
const q = new Quene(1000);
q.enquene(() => {
console.log(new Date(), 1);
});
q.enquene(() => {
console.log(new Date(), 2);
});
q.enquene(() => {
console.log(new Date(), 3);
});
网友评论