Improve YggdrasilSpacing API
diff --git a/demo/src/routes/spacer.ts b/demo/src/routes/spacer.ts
index 641ac2f..b6aab06 100644
--- a/demo/src/routes/spacer.ts
+++ b/demo/src/routes/spacer.ts
@@ -5,13 +5,13 @@
import { DemoServer } from "../server";
export const spacer = DemoServer.defineRoute("GET", "/spacer", async (ygg) => {
- const spacer = new YggdrasilSpacer(100);
+ const spacer = new YggdrasilSpacer(1000);
const tasks = [];
for (let i = 0; i < 10; ++i) {
tasks.push((async () => {
console.log(i + " is waiting for dispatch...");
- await spacer.waitForDispatch();
+ await spacer.enqueueTask(i === 4 ? () => new Promise(res => setTimeout(res, 5000)) : undefined);
console.log(i);
})());
}
@@ -25,7 +25,7 @@
});
console.log("10 is waiting for dispatch...");
- await spacer.waitForDispatch();
+ await spacer.enqueueTask();
console.log(10);
return new Response("Done", { status: 200 });
diff --git a/docs/docs/features/spacer.md b/docs/docs/features/spacer.md
index 3c1e70e..cc1b3d7 100644
--- a/docs/docs/features/spacer.md
+++ b/docs/docs/features/spacer.md
@@ -11,7 +11,7 @@
## Usage
Simply create a `YggdrasilSpacer` object with your desired spacing,
-then await `waitForDispatch` before doing each task:
+then use `enqueueTask` to schedule each task for execution:
```ts title="src/handler.ts"
// Wait 100ms between each API request
@@ -20,13 +20,18 @@
const tasks = [];
for (const item of items) {
- tasks.push((async () => {
- await spacer.waitForDispatch();
+ tasks.push(spacer.enqueueTask(async () => {
await api.updateItem(item);
- })());
+ }));
}
await Promise.all(tasks);
console.log("Done updating all items (with minimum 100ms spacing between each update)!");
-```
\ No newline at end of file
+```
+
+The asynchronous task passed to `enqueueTask` will be called automatically
+when time spacing allows. The Promise returned by `enqueueTask` resolves
+when the task is completed. Passing a task function is optional; if it is
+omitted, `enqueueTask` resolves and the next task's spacing starts
+immediately when the current task is triggered.
\ No newline at end of file
diff --git a/yggdrasil/package.json b/yggdrasil/package.json
index 2ada862..9a66207 100644
--- a/yggdrasil/package.json
+++ b/yggdrasil/package.json
@@ -1,7 +1,7 @@
{
"name": "@jottocraft/yggdrasil",
"description": "A simple and flexible TypeScript library for streamlining web request handling.",
- "version": "0.0.1-alpha.6",
+ "version": "0.0.1-alpha.7",
"license": "LGPL-2.1-only",
"author": "jottocraft <[email protected]>",
"main": "lib/index.js",
diff --git a/yggdrasil/src/YggdrasilSpacer.ts b/yggdrasil/src/YggdrasilSpacer.ts
index 6922b07..840beb8 100644
--- a/yggdrasil/src/YggdrasilSpacer.ts
+++ b/yggdrasil/src/YggdrasilSpacer.ts
@@ -13,27 +13,51 @@
}
/**
- * Registers a new task and returns a Promise that resolves when the task should be executed.
+ * Registers a new task that will be triggered when the spacing allows it to be.
+ * @param task An asynchronous function that executes the task. If provided, the timer for spacing the next task starts when the function resolves. Otherwise, the timer for spacing the next task starts immediately when this task is triggered.
+ * @returns A Promise that resolves when the task has been executed. If a task function was provided, the returned Promise resolves when the task function resolves. Otherwise, the returned Promise resolves when the task is triggered.
*/
- waitForDispatch() {
+ enqueueTask(task?: () => Promise<unknown>) {
return new Promise<void>((resolve, reject) => {
- const now = new Date().getTime();
- if (((now - this.#lastDispatch) >= this.#spacingMs) && !this.#tasks.length) {
- this.#lastDispatch = now;
+ const thisTaskTarget = new EventTarget();
+
+ thisTaskTarget.addEventListener("dispatch", async () => {
+ if (task) {
+ try {
+ await task();
+ } catch(e) {
+ reject(e);
+ }
+ }
+
+ this.#lastDispatchCompletion = new Date().getTime();
+ this.#tasks.shift();
+
resolve();
- } else {
- const thisTaskEndsAt = (this.#tasks.length ? this.#tasks[this.#tasks.length - 1] : this.#lastDispatch) + this.#spacingMs;
- this.#tasks.push(thisTaskEndsAt);
- setTimeout(() => {
- this.#lastDispatch = thisTaskEndsAt;
- this.#tasks.shift();
- resolve();
- }, thisTaskEndsAt - now);
- }
+
+ if (this.#tasks.length) {
+ setTimeout(() => {
+ this.#tasks[0].dispatchEvent(new CustomEvent("dispatch"));
+ }, this.#spacingMs);
+ }
+ });
+
+ this.#tasks.push(thisTaskTarget);
+
+ if (this.#tasks.length === 1) {
+ const now = new Date().getTime();
+ if ((now - this.#lastDispatchCompletion) >= this.#spacingMs) {
+ thisTaskTarget.dispatchEvent(new CustomEvent("dispatch"));
+ } else {
+ setTimeout(() => {
+ thisTaskTarget.dispatchEvent(new CustomEvent("dispatch"));
+ }, this.#lastDispatchCompletion + this.#spacingMs - now);
+ }
+ }
});
}
- #tasks: number[] = [];
- #lastDispatch: number = 0;
+ #tasks: EventTarget[] = [];
+ #lastDispatchCompletion: number = 0;
#spacingMs: number;
};
\ No newline at end of file