class Queue {
_tasks = [];
constructor() {}
// 添加任务
task(ms, cb) {
this._tasks.push({ ms, cb });
// 实现链式调用
return this;
}
// 开启执行
start() {
if (this._tasks.length) {
// 取出第一个事件
const { ms, cb } = this._tasks[0];
setTimeout(() => {
cb.apply(this);
this._tasks.shift();
// 下面这步实现依次调用
if (this._tasks.length) {
this.start();
}
}, ms);
}
}
}
// test
const startTime = Date.now();
new Queue()
.task(1000, () => {
console.log(1);
console.log(Date.now() - startTime);
})
.task(2000, () => {
console.log(2);
console.log(Date.now() - startTime);
})
.task(1000, () => {
console.log(3);
console.log(Date.now() - startTime);
})
.start();
使用
new Queue()
.task(1000, () => {
console.log(1);
})
.task(2000, () => {
console.log(2);
})
.task(1000, () => {
console.log(3);
})
.start();