1.创建一个延时器
function timeout(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
}
2.声明一个class类,在构造器中定义相应的变量
class SuperTask {
constructor(parallelCount = 2) {
this.parallelCount = parallelCount;
this.tasks = [];
this.runningCount = 0;
}
}
3.当执行队列一面的并发数量低于设定的最大并发数量时自动补位
class SuperTask {
......
add(task) {
return new Promise((resolve, reject) => {
this.tasks.push({
task,
resolve,
reject,
});
this._run();
});
}
}
4.执行队列,判断正在执行的数量是否小于最大并发数量,并且等待队列的数量大于0时,再次进行补位执行
class SuperTask {
......
_run() {
while (this.runningCount < this.parallelCount && this.tasks.length > 0) {
const { task, resolve, reject } = this.tasks.shift();
this.runningCount++;
task()
.then(resolve, reject)
.finally(() => {
this.runningCount--;
this._run();
});
}
}
}
5.执行导出
const superTask = new SuperTask();
export function addTask(time, fucn) {
superTask
.add(() => timeout(time ? time : null))
.then(() => {
fucn();
console.log(`任务完成`);
});
}
6.使用
import { addTask } from "....";
addTask(100, fn1);
addTask(200, fn2);