rvx
Version:
A signal based rendering library
65 lines • 2.03 kB
JavaScript
import { teardown } from "../core/lifecycle.js";
export class Queue {
#queue = [];
#blocked = -1;
#controller = undefined;
#running = undefined;
constructor() {
teardown(() => this.#abort());
}
#abort() {
const queue = this.#queue;
while (queue.length > 0 && !queue[0].blocking) {
queue.shift();
this.#blocked--;
}
this.#controller?.abort();
}
#run() {
if (this.#running === undefined) {
this.#running = (async () => {
let task;
while (task = this.#queue.shift()) {
this.#blocked--;
if (task.blocking) {
try {
task.resolve(await task.task());
}
catch (error) {
task.reject(error);
}
}
else {
const controller = new AbortController();
this.#controller = controller;
try {
await task.task(controller.signal);
}
catch (error) {
void Promise.reject(error);
}
this.#controller = undefined;
}
}
this.#blocked--;
this.#running = undefined;
})();
}
}
sideEffect(task) {
if (this.#blocked >= 0) {
return;
}
this.#abort();
this.#queue.push({ blocking: false, task, resolve: undefined, reject: undefined });
this.#run();
}
block(task) {
return new Promise((resolve, reject) => {
this.#abort();
this.#blocked = this.#queue.push({ blocking: true, task, resolve, reject });
this.#run();
});
}
}
//# sourceMappingURL=queue.js.map