whale-plus
Version:
A Component Library for Vue 3
76 lines (73 loc) • 1.51 kB
JavaScript
import { EventEmitter } from './EventEmitter.mjs';
class Task {
constructor(fn, payload) {
this.fn = fn;
this.payload = payload;
}
run() {
return this.fn(this.payload);
}
}
class TaskQueue extends EventEmitter {
constructor(concurrency = 4) {
super();
this.tasks = /* @__PURE__ */ new Set();
this.currentCount = 0;
this.status = "paused";
this.concurrency = 4;
this.concurrency = concurrency;
}
add(...tasks) {
for (const t of tasks) {
this.tasks.add(t);
}
}
addAndStart(...tasks) {
this.add(...tasks);
this.start();
}
start() {
if (this.status === "running") {
return;
}
if (this.tasks.size === 0) {
this.emit("drain");
return;
}
this.status = "running";
this.emit("start");
this.runNext();
}
takeHeadTask() {
const task = this.tasks.values().next().value;
if (task) {
this.tasks.delete(task);
}
return task;
}
runNext() {
if (this.status !== "running") {
return;
}
if (this.currentCount >= this.concurrency) {
return;
}
const task = this.takeHeadTask();
if (!task) {
this.status = "paused";
this.emit("drain");
return;
}
this.currentCount++;
Promise.resolve(task.run()).finally(() => {
this.currentCount--;
this.runNext();
});
}
pause() {
this.status = "paused";
this.emit("pause");
}
}
export { Task, TaskQueue };
//# sourceMappingURL=TaskQueue.mjs.map