time-queues 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt ADDED
@@ -0,0 +1,95 @@
1
+ # time-queues
2
+
3
+ > Lightweight async task scheduling and concurrency control for JavaScript: schedulers, idle/frame/limited queues, throttle, debounce, batch, page lifecycle, random delays.
4
+
5
+ - NPM: https://npmjs.org/package/time-queues
6
+ - GitHub: https://github.com/uhop/time-queues
7
+ - Wiki: https://github.com/uhop/time-queues/wiki
8
+ - License: BSD-3-Clause
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm install time-queues
14
+ ```
15
+
16
+ ## Quick start
17
+
18
+ ```js
19
+ import sleep from 'time-queues/sleep.js';
20
+ import {Scheduler, repeat} from 'time-queues/Scheduler.js';
21
+ import {batch} from 'time-queues/batch.js';
22
+
23
+ // Simple delay
24
+ await sleep(1000);
25
+
26
+ // Run a task every 5 seconds
27
+ const scheduler = new Scheduler();
28
+ scheduler.enqueue(repeat(({task, scheduler}) => {
29
+ console.log('tick');
30
+ }, 5000), 5000);
31
+
32
+ // Fetch URLs, max 3 at a time
33
+ const results = await batch(
34
+ urls.map(url => () => fetch(url).then(r => r.json())),
35
+ 3
36
+ );
37
+ ```
38
+
39
+ ## Modules
40
+
41
+ ### Queues
42
+
43
+ - **Scheduler** (`time-queues/Scheduler.js`) — time-based task scheduling with delays, dates, and repeats. Extends MicroTaskQueue. Uses a min-heap. Exports: `Scheduler`, `Task`, `repeat(fn, delay)`, `scheduler` (global instance).
44
+ - **IdleQueue** (`time-queues/IdleQueue.js`) — run tasks during browser idle periods via `requestIdleCallback()`. Extends ListQueue. Exports: `IdleQueue`, `idleQueue` (global instance), `defer(fn)`.
45
+ - **FrameQueue** (`time-queues/FrameQueue.js`) — run tasks in animation frames via `requestAnimationFrame()`. Extends ListQueue. Exports: `FrameQueue`, `frameQueue` (global instance).
46
+ - **LimitedQueue** (`time-queues/LimitedQueue.js`) — concurrency-controlled async queue. Extends ListQueue. Exports: `LimitedQueue`, `Task`.
47
+ - **PageWatcher** (`time-queues/PageWatcher.js`) — react to page lifecycle changes (active, passive, hidden, frozen, terminated). Extends ListQueue. Exports: `PageWatcher`, `watchStates(states, fn)`, `pageWatcher` (global instance).
48
+
49
+ ### Utility functions
50
+
51
+ - **sleep** (`time-queues/sleep.js`) — `sleep(ms | Date): Promise<void>`. Promise-based delay.
52
+ - **defer** (`time-queues/defer.js`) — `defer(fn): void`. Execute on next tick via `requestIdleCallback`/`setImmediate`/`setTimeout`. Also exports `scheduleDefer(fn): Promise`.
53
+ - **throttle** (`time-queues/throttle.js`) — `throttle(fn, ms): fn`. Rate-limit: execute immediately, ignore calls until timeout expires.
54
+ - **debounce** (`time-queues/debounce.js`) — `debounce(fn, ms): fn`. Delay until input stabilizes.
55
+ - **sample** (`time-queues/sample.js`) — `sample(fn, ms): fn`. Execute at regular intervals with last seen args.
56
+ - **audit** (`time-queues/audit.js`) — `audit(fn, ms): fn`. Collect then execute after delay with last seen args.
57
+ - **batch** (`time-queues/batch.js`) — `batch(fns, limit?): Promise<results[]>`. Run async operations with concurrency limit (default: 5).
58
+
59
+ ### Supporting classes
60
+
61
+ - **Throttler** (`time-queues/Throttler.js`) — key-based rate limiting with vacuum cleanup. Methods: `getDelay(key)`, `wait(key)`, `startVacuum()`, `stopVacuum()`.
62
+ - **Retainer** (`time-queues/Retainer.js`) — resource lifecycle management with reference counting. Methods: `get(): Promise<value>`, `release(): Promise<void>`.
63
+ - **Counter** (`time-queues/Counter.js`) — numeric counter with async waiting. Methods: `increment()`, `decrement()`, `advance(delta)`, `waitForZero()`, `waitFor(target)`.
64
+ - **CancelTaskError** (`time-queues/CancelTaskError.js`) — `Error` subclass for task cancellation signals.
65
+
66
+ ### Base classes
67
+
68
+ - **MicroTask** (`time-queues/MicroTask.js`) — base task unit with lazy promise creation. Methods: `makePromise()`, `resolve(value)`, `cancel(error)`.
69
+ - **MicroTaskQueue** (`time-queues/MicroTaskQueue.js`) — abstract queue base class. Methods: `enqueue(fn)`, `dequeue(task)`, `schedule(fn)`, `clear()`, `pause()`, `resume()`.
70
+ - **ListQueue** (`time-queues/ListQueue.js`) — linked-list queue implementation extending MicroTaskQueue. Adds `startQueue()` lifecycle.
71
+
72
+ ### Random utilities
73
+
74
+ - **random-dist** (`time-queues/random-dist.js`) — `uniform(min, max)`, `normal(mean, stdDev, skewness?)`, `expo(lambda)`, `pareto(min, alpha)`.
75
+ - **random-sleep** (`time-queues/random-sleep.js`) — `randomUniformSleep(min, max)`, `randomNormalSleep(mean, stdDev)`, `randomExpoSleep(lambda, scale)`, `randomParetoSleep(min, ratio)`, `randomSleep(max)`. Each returns `() => Promise<void>`.
76
+
77
+ ### Page load helpers
78
+
79
+ - **whenDomLoaded** (`time-queues/when-dom-loaded.js`) — `whenDomLoaded(fn)`. Also exports `scheduleWhenDomLoaded(fn): Promise`, `remove(fn): boolean`.
80
+ - **whenLoaded** (`time-queues/when-loaded.js`) — `whenLoaded(fn)`. Also exports `scheduleWhenLoaded(fn): Promise`, `remove(fn): boolean`.
81
+
82
+ ## Key concepts
83
+
84
+ - All modules are **ESM** with `import ... from 'time-queues/<module>.js'`.
85
+ - **Inheritance**: `MicroTaskQueue` → `ListQueue` → `IdleQueue`/`FrameQueue`/`LimitedQueue`/`PageWatcher`. `Scheduler` extends `MicroTaskQueue` directly.
86
+ - **Lazy promises** — only created when `.makePromise()` is called or via `schedule()`.
87
+ - **Clean cancellation** — all tasks support cancellation via `CancelTaskError`.
88
+ - **Graceful degradation** — feature detection for browser APIs, works in Node.js/Bun/Deno.
89
+ - **TypeScript** — built-in `.d.ts` declarations for all modules.
90
+
91
+ ## Links
92
+
93
+ - Docs: https://github.com/uhop/time-queues/wiki
94
+ - npm: https://www.npmjs.com/package/time-queues
95
+ - Full LLM reference: https://github.com/uhop/time-queues/blob/master/llms-full.txt
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "time-queues",
3
- "version": "1.3.0",
4
- "description": "Time queues to organize multitasking and scheduled tasks.",
3
+ "version": "1.3.1",
4
+ "description": "Lightweight async task scheduling and concurrency control: schedulers, idle/frame/limited queues, throttle, debounce, batch, page lifecycle, random delays. Browsers, Node.js, Deno, Bun.",
5
5
  "type": "module",
6
6
  "types": "./src/index.d.ts",
7
7
  "exports": {
@@ -21,8 +21,14 @@
21
21
  "ts-test": "tape6 --flags FO '/ts-tests/test-*.*ts'",
22
22
  "ts-test:bun": "tape6-bun --flags FO '/ts-tests/test-*.*ts'",
23
23
  "ts-test:deno": "tape6-deno --flags FO '/ts-tests/test-*.*ts'",
24
- "lint": "prettier --check src/ tests/ wiki/",
25
- "lint:fix": "prettier --write src/ tests/ wiki/",
24
+ "ts-test:proc": "tape6-proc --flags FO '/ts-tests/test-*.*ts'",
25
+ "ts-test:proc:bun": "bun run `tape6-proc --self` --flags FO '/ts-tests/test-*.*ts'",
26
+ "ts-test:proc:deno": "deno run -A `tape6-proc --self` --flags FO -r -A '/ts-tests/test-*.*ts'",
27
+ "ts-test:seq": "tape6-seq --flags FO '/ts-tests/test-*.*ts'",
28
+ "ts-test:seq:bun": "bun run `tape6-seq --self` --flags FO '/ts-tests/test-*.*ts'",
29
+ "ts-test:seq:deno": "deno run -A `tape6-seq --self` --flags FO '/ts-tests/test-*.*ts'",
30
+ "lint": "prettier --check .",
31
+ "lint:fix": "prettier --write .",
26
32
  "start": "tape6-server --trace"
27
33
  },
28
34
  "repository": {
@@ -30,9 +36,25 @@
30
36
  "url": "git+ssh://git@github.com/uhop/time-queues.git"
31
37
  },
32
38
  "keywords": [
39
+ "scheduler",
40
+ "task-queue",
41
+ "async-queue",
42
+ "concurrency",
43
+ "throttle",
44
+ "debounce",
45
+ "rate-limit",
46
+ "batch",
47
+ "sleep",
48
+ "defer",
49
+ "idle-queue",
50
+ "requestIdleCallback",
51
+ "requestAnimationFrame",
52
+ "page-lifecycle",
33
53
  "timer",
34
54
  "time",
35
- "queue"
55
+ "queue",
56
+ "esm",
57
+ "typescript"
36
58
  ],
37
59
  "author": "Eugene Lazutkin <eugene.lazutkin@gmail.com> (https://www.lazutkin.com/)",
38
60
  "funding": "https://github.com/sponsors/uhop",
@@ -40,11 +62,16 @@
40
62
  "bugs": {
41
63
  "url": "https://github.com/uhop/time-queues/issues"
42
64
  },
65
+ "github": "https://github.com/uhop/time-queues",
43
66
  "homepage": "https://github.com/uhop/time-queues#readme",
67
+ "llms": "https://raw.githubusercontent.com/uhop/time-queues/master/llms.txt",
68
+ "llmsFull": "https://raw.githubusercontent.com/uhop/time-queues/master/llms-full.txt",
44
69
  "files": [
45
70
  "/src",
46
71
  "LICENSE",
47
- "README.md"
72
+ "README.md",
73
+ "llms.txt",
74
+ "llms-full.txt"
48
75
  ],
49
76
  "tape6": {
50
77
  "tests": [
@@ -59,12 +86,13 @@
59
86
  }
60
87
  },
61
88
  "devDependencies": {
62
- "@types/node": "^25.2.3",
63
- "tape-six": "^1.7.0",
64
- "tape-six-proc": "^1.2.2",
89
+ "@types/node": "^25.3.0",
90
+ "prettier": "^3.8.1",
91
+ "tape-six": "^1.7.2",
92
+ "tape-six-proc": "^1.2.3",
65
93
  "typescript": "^5.9.3"
66
94
  },
67
95
  "dependencies": {
68
- "list-toolkit": "^2.2.6"
96
+ "list-toolkit": "^2.3.0"
69
97
  }
70
98
  }
@@ -2,7 +2,8 @@
2
2
  * A cancellation error that is thrown when a microtask is canceled.
3
3
  */
4
4
  export declare class CancelTaskError extends Error {
5
- constructor(message: string = 'Task was canceled', options?: ErrorOptions);
5
+ name: 'CancelTaskError';
6
+ constructor(message?: string, options?: ErrorOptions);
6
7
  }
7
8
 
8
9
  export default CancelTaskError;
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./CancelTaskError.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export class CancelTaskError extends Error {
6
4
  constructor(message = 'Task was canceled', options) {
7
5
  super(message, options);
package/src/Counter.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./Counter.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export class Counter {
6
4
  constructor(initial = 0) {
7
5
  this.count = initial;
@@ -44,7 +44,7 @@ export declare class FrameQueue extends ListQueue {
44
44
 
45
45
  /**
46
46
  * Schedules a task to run in the next frame.
47
- * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with function's arguments. Otherwise, it is resolved with the function's return value.
47
+ * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with the function's arguments. Otherwise, it is resolved with the function's return value.
48
48
  * @returns The task object.
49
49
  */
50
50
  schedule(
@@ -82,4 +82,4 @@ export declare class FrameQueue extends ListQueue {
82
82
  */
83
83
  export const frameQueue: FrameQueue;
84
84
 
85
- export default FrameQueue;
85
+ export default frameQueue;
package/src/FrameQueue.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./FrameQueue.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import List from 'list-toolkit/list.js';
6
4
  import ListQueue from './ListQueue.js';
7
5
 
@@ -51,7 +51,7 @@ export declare class IdleQueue extends ListQueue {
51
51
 
52
52
  /**
53
53
  * Schedules a task to run in the next idle period.
54
- * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with function's arguments. Otherwise, it is resolved with the function's return value.
54
+ * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with the function's arguments. Otherwise, it is resolved with the function's return value.
55
55
  * @returns The task object.
56
56
  */
57
57
  schedule(
@@ -96,4 +96,4 @@ export const defer: (
96
96
  fn: ({deadline: IdleDeadline, task: Task, queue: IdleQueue}) => unknown
97
97
  ) => Task;
98
98
 
99
- export default IdleQueue;
99
+ export default idleQueue;
package/src/IdleQueue.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./IdleQueue.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import List from 'list-toolkit/list.js';
6
4
  import ListQueue from './ListQueue.js';
7
5
 
@@ -15,7 +15,7 @@ export declare class LimitedQueue extends ListQueue {
15
15
  stopQueue: (() => void) | null;
16
16
 
17
17
  /**
18
- * Creates a new list queue.
18
+ * Creates a new limited queue.
19
19
  * @param limit The maximum number of tasks that can be run in parallel.
20
20
  * @param paused Whether the queue should start paused.
21
21
  */
@@ -33,7 +33,7 @@ export declare class LimitedQueue extends ListQueue {
33
33
 
34
34
  /**
35
35
  * Set the maximum number of tasks that can be run in parallel.
36
- * @param limit The new maximum number of tasks that can be run in parallel. It can dynamically add more tasks if the current number of tasks is less than the new limit.
36
+ * @param limit The new maximum number of tasks that can be run in parallel. Setting a higher limit may immediately start additional tasks.
37
37
  */
38
38
  set taskLimit(limit: number);
39
39
 
@@ -48,7 +48,7 @@ export declare class LimitedQueue extends ListQueue {
48
48
  get isIdle(): boolean;
49
49
 
50
50
  /**
51
- * Wait for queue to become idle.
51
+ * Waits for the queue to become idle.
52
52
  * @returns A promise that resolves when the queue becomes idle. If the queue is already idle, the promise is resolved immediately.
53
53
  */
54
54
  waitForIdle(): Promise<void>;
@@ -69,7 +69,7 @@ export declare class LimitedQueue extends ListQueue {
69
69
 
70
70
  /**
71
71
  * Schedules a microtask.
72
- * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with function's arguments. Otherwise, it is resolved with the function's return value.
72
+ * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with the function's arguments. Otherwise, it is resolved with the function's return value.
73
73
  * @returns The task object.
74
74
  */
75
75
  schedule(fn: (() => unknown) | null | undefined): Task;
@@ -45,7 +45,7 @@ export declare class ListQueue extends MicroTaskQueue {
45
45
 
46
46
  /**
47
47
  * Schedules a microtask.
48
- * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with function's arguments. Otherwise, it is resolved with the function's return value.
48
+ * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with the function's arguments. Otherwise, it is resolved with the function's return value.
49
49
  * @returns The task object.
50
50
  */
51
51
  schedule(fn: (() => unknown) | null | undefined): MicroTask;
package/src/ListQueue.js CHANGED
@@ -1,14 +1,20 @@
1
1
  // @ts-self-types="./ListQueue.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import List from 'list-toolkit/list.js';
6
4
  import MicroTaskQueue from './MicroTaskQueue.js';
7
5
 
6
+ /**
7
+ * ListQueue extends MicroTaskQueue with linked-list task storage.
8
+ * AI-NOTE: This is the concrete base class most specialized queues extend.
9
+ * Key pattern: startQueue() returns a stop function (or null if not started).
10
+ * @see IdleQueue, FrameQueue, LimitedQueue, Scheduler - All extend ListQueue
11
+ */
8
12
  export class ListQueue extends MicroTaskQueue {
9
13
  constructor(paused) {
10
14
  super(paused);
15
+ // AI-NOTE: Using list-toolkit List for O(1) push/pop operations
11
16
  this.list = new List();
17
+ // AI-NOTE: stopQueue holds the stop function returned by startQueue(), or null
12
18
  this.stopQueue = null;
13
19
  }
14
20
 
@@ -19,6 +25,7 @@ export class ListQueue extends MicroTaskQueue {
19
25
  pause() {
20
26
  if (!this.paused) {
21
27
  super.pause();
28
+ // AI-NOTE: Pattern: call stop function, then null it
22
29
  if (this.stopQueue) this.stopQueue = (this.stopQueue(), null);
23
30
  }
24
31
  return this;
@@ -27,6 +34,7 @@ export class ListQueue extends MicroTaskQueue {
27
34
  resume() {
28
35
  if (this.paused) {
29
36
  super.resume();
37
+ // AI-NOTE: Auto-start processing if tasks exist and not already running
30
38
  if (!this.list.isEmpty) {
31
39
  this.stopQueue = this.startQueue();
32
40
  }
@@ -37,6 +45,7 @@ export class ListQueue extends MicroTaskQueue {
37
45
  enqueue(fn) {
38
46
  const task = super.enqueue(fn);
39
47
  this.list.pushBack(task);
48
+ // AI-NOTE: Auto-start queue on first task if not paused and not running
40
49
  if (!this.paused && !this.stopQueue) this.stopQueue = this.startQueue();
41
50
  return task;
42
51
  }
@@ -44,6 +53,7 @@ export class ListQueue extends MicroTaskQueue {
44
53
  dequeue(task) {
45
54
  task.cancel();
46
55
  this.list.removeNode(task);
56
+ // AI-NOTE: Auto-stop queue when empty (unless paused)
47
57
  if (!this.paused && this.list.isEmpty && this.stopQueue)
48
58
  this.stopQueue = (this.stopQueue(), null);
49
59
  return this;
@@ -60,7 +70,12 @@ export class ListQueue extends MicroTaskQueue {
60
70
  return this;
61
71
  }
62
72
 
63
- // API to be overridden in subclasses
73
+ /**
74
+ * Start processing the queue - MUST be overridden by subclasses.
75
+ * AI-NOTE: This is the abstract method pattern - base returns null.
76
+ * Subclasses return a function that stops the processing.
77
+ * @returns {Function|null} Stop function or null if not started
78
+ */
64
79
  startQueue() {
65
80
  return null;
66
81
  }
@@ -31,6 +31,11 @@ export declare class MicroTask {
31
31
  */
32
32
  get promise(): Promise<unknown> | null;
33
33
 
34
+ /**
35
+ * Whether the microtask has been settled (resolved or canceled).
36
+ */
37
+ get settled(): boolean;
38
+
34
39
  /**
35
40
  * Resolves the microtask, if a promise is created.
36
41
  * @param value The value to resolve the microtask with.
package/src/MicroTask.js CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  import CancelTaskError from './CancelTaskError.js';
4
4
 
5
+ /**
6
+ * Base class for deferred task execution with lazy promise creation.
7
+ * AI-NOTE: Promises are created lazily via makePromise() - not in constructor.
8
+ * This allows tasks to be created without immediate promise overhead.
9
+ */
5
10
  export class MicroTask {
6
11
  #promise;
7
12
  #resolve;
@@ -9,17 +14,25 @@ export class MicroTask {
9
14
  #settled;
10
15
  constructor(fn) {
11
16
  this.fn = fn;
17
+ // AI-NOTE: Private fields initialized to null - lazy initialization pattern
12
18
  this.#promise = null;
13
19
  this.#resolve = null;
14
20
  this.#reject = null;
21
+ this.#settled = false;
15
22
  this.isCanceled = false;
16
23
  }
24
+ // AI-NOTE: Returns null until makePromise() is called - this is intentional
17
25
  get promise() {
18
26
  return this.#promise;
19
27
  }
20
28
  get settled() {
21
29
  return this.#settled;
22
30
  }
31
+ /**
32
+ * Creates the promise and resolution functions.
33
+ * AI-NOTE: Uses Promise.withResolvers() when available (modern environments),
34
+ * falls back to manual Promise constructor for broader compatibility.
35
+ */
23
36
  makePromise() {
24
37
  if (this.#promise) return this;
25
38
  if (typeof Promise.withResolvers == 'function') {
@@ -45,6 +58,10 @@ export class MicroTask {
45
58
  }
46
59
  return this;
47
60
  }
61
+ /**
62
+ * Cancel the task with optional error cause.
63
+ * AI-NOTE: Always rejects with CancelTaskError to distinguish from other errors.
64
+ */
48
65
  cancel(error) {
49
66
  this.isCanceled = true;
50
67
  if (this.#reject) {
@@ -42,8 +42,8 @@ export declare class MicroTaskQueue {
42
42
  /**
43
43
  * Schedules a microtask with a promise for execution.
44
44
  * This can be overridden in subclasses if more arguments are needed.
45
- * @param fn The function to execute when the microtask is scheduled, it can be an async function.
46
- * @param args Additional arguments to pass to `enqueue()`. It is there to accommodate custom implementations in subclasses.
45
+ * @param fn The function to execute when the microtask is scheduled. It can be an async function.
46
+ * @param args Additional arguments to pass to `enqueue()`. They are there to accommodate custom implementations in subclasses.
47
47
  * @returns The scheduled microtask.
48
48
  */
49
49
  schedule(fn: (() => unknown) | null | undefined, ...args: unknown[]): MicroTask;
@@ -1,14 +1,19 @@
1
1
  // @ts-self-types="./MicroTaskQueue.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import MicroTask from './MicroTask.js';
6
4
 
5
+ /**
6
+ * Base queue class for managing task lifecycle.
7
+ * AI-NOTE: This is an abstract base class - concrete implementations should extend
8
+ * ListQueue for actual task storage and processing.
9
+ * @see ListQueue - The primary class for queue implementations
10
+ */
7
11
  export class MicroTaskQueue {
8
12
  constructor(paused) {
9
13
  this.paused = Boolean(paused);
10
14
  }
11
15
  // API to be overridden in subclasses
16
+ // AI-NOTE: Base implementation returns true - subclasses override with actual logic
12
17
  get isEmpty() {
13
18
  return true;
14
19
  }
@@ -20,6 +25,11 @@ export class MicroTaskQueue {
20
25
  this.paused = false;
21
26
  return this;
22
27
  }
28
+ /**
29
+ * Enqueue a function for execution.
30
+ * AI-NOTE: Creates MicroTask but does NOT create promise automatically.
31
+ * Call task.makePromise() if promise access is needed.
32
+ */
23
33
  enqueue(fn) {
24
34
  const task = new MicroTask(fn);
25
35
  return task;
@@ -31,7 +41,11 @@ export class MicroTaskQueue {
31
41
  clear() {
32
42
  return this;
33
43
  }
34
- // Generic API
44
+ /**
45
+ * Schedule a function with automatic promise creation.
46
+ * AI-NOTE: This is the convenience method - it calls both enqueue() and makePromise().
47
+ * Returns a MicroTask with an active promise.
48
+ */
35
49
  schedule(fn, ...args) {
36
50
  fn ||= MicroTaskQueue.returnArgs;
37
51
  const task = this.enqueue(
@@ -33,7 +33,7 @@ export declare class PageWatcher extends ListQueue {
33
33
  /**
34
34
  * Enqueues a task.
35
35
  * @param fn The function to execute.
36
- * @param initialize Whether the function should be executed before the state changes.
36
+ * @param initialize Whether the function should be called immediately with the current state.
37
37
  * @returns The task object.
38
38
  */
39
39
  enqueue(
@@ -90,4 +90,4 @@ export declare const watchStates: (
90
90
  */
91
91
  export declare const pageWatcher: PageWatcher;
92
92
 
93
- export default PageWatcher;
93
+ export default pageWatcher;
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./PageWatcher.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import ListQueue from './ListQueue.js';
6
4
 
7
5
  // Based on information from https://developer.chrome.com/docs/web-platform/page-lifecycle-api
package/src/Retainer.d.ts CHANGED
@@ -13,7 +13,7 @@ export declare interface RetainerOptions<T = unknown> {
13
13
  /**
14
14
  * The retention period in milliseconds.
15
15
  */
16
- retentionPeriod: number;
16
+ retentionPeriod?: number;
17
17
  }
18
18
 
19
19
  /**
@@ -55,14 +55,14 @@ export declare class Retainer<T = unknown> implements RetainerOptions<T> {
55
55
  * Retrieves the retained value.
56
56
  * @returns The retained value as a promise.
57
57
  */
58
- async get(): Promise<T>;
58
+ get(): Promise<T>;
59
59
 
60
60
  /**
61
61
  * Releases the retained value.
62
- * @param immediately Whether to release the value immediately. Otherwise it'll be retained for the retention period.
62
+ * @param immediately Whether to release the value immediately. Otherwise, it will be retained for the retention period.
63
63
  * @returns The retainer object.
64
64
  */
65
- async release(immediately?: boolean): Promise<this>;
65
+ release(immediately?: boolean): Promise<this>;
66
66
  }
67
67
 
68
68
  export default Retainer;
package/src/Retainer.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./Retainer.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export class Retainer {
6
4
  constructor({create, destroy, retentionPeriod = 1_000}) {
7
5
  if (!create || !destroy) throw new Error('Retainer: create and destroy are required');
@@ -55,9 +55,10 @@ export declare class Task extends MicroTask {
55
55
  /**
56
56
  * Cancels the microtask, if a promise is created.
57
57
  * If the microtask is canceled, the promise will be rejected with a CancelTaskError.
58
+ * @param error The optional error to use as the cause of the cancellation.
58
59
  * @returns The microtask.
59
60
  */
60
- cancel(): this;
61
+ cancel(error?: Error): this;
61
62
  }
62
63
 
63
64
  /**
@@ -71,7 +72,7 @@ export declare class Scheduler extends MicroTaskQueue {
71
72
  paused: boolean;
72
73
 
73
74
  /**
74
- * The tolerance for comparing starting time of tasks.
75
+ * The tolerance for comparing starting times of tasks.
75
76
  * This allows for small timing differences in task execution.
76
77
  */
77
78
  tolerance: number;
@@ -79,7 +80,7 @@ export declare class Scheduler extends MicroTaskQueue {
79
80
  /**
80
81
  * Creates a new scheduler.
81
82
  * @param paused Whether the scheduler should start in a paused state.
82
- * @param tolerance The tolerance for comparing starting time of tasks (default is 4ms).
83
+ * @param tolerance The tolerance for comparing starting times of tasks (default is 4ms).
83
84
  */
84
85
  constructor(paused?: boolean, tolerance?: number);
85
86
 
@@ -112,7 +113,7 @@ export declare class Scheduler extends MicroTaskQueue {
112
113
 
113
114
  /**
114
115
  * Schedules a task to run in the future.
115
- * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with function's arguments. Otherwise, it is resolved with the function's return value.
116
+ * @param fn The function to execute. If `undefined` or `null`, the task's promise will be resolved with the function's arguments. Otherwise, it is resolved with the function's return value.
116
117
  * @param delay The delay before the task is executed. It can be a number of milliseconds or a `Date` object as an absolute time.
117
118
  * @returns The task object that was scheduled.
118
119
  */
package/src/Scheduler.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./Scheduler.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import MinHeap from 'list-toolkit/heap.js';
6
4
  import MicroTask from './MicroTask.js';
7
5
  import MicroTaskQueue from './MicroTaskQueue.js';
@@ -90,6 +88,7 @@ export class Scheduler extends MicroTaskQueue {
90
88
  this.queue.array.forEach(task => task.cancel());
91
89
  this.queue.clear();
92
90
  if (!paused) this.resume();
91
+ return this;
93
92
  }
94
93
 
95
94
  startQueue() {
@@ -71,6 +71,11 @@ export declare class Throttler implements ThrottlerOptions {
71
71
  */
72
72
  wait(key: unknown): Promise<void>;
73
73
 
74
+ /**
75
+ * Removes expired keys from the last seen map.
76
+ */
77
+ vacuum(): void;
78
+
74
79
  /**
75
80
  * Retrieves the vacuuming state.
76
81
  * @returns `true` if the vacuuming is active, `false` otherwise.
@@ -79,14 +84,14 @@ export declare class Throttler implements ThrottlerOptions {
79
84
 
80
85
  /**
81
86
  * Starts the vacuum process.
82
- * The vacuum process removes keys that expired.
87
+ * The vacuum process removes expired keys.
83
88
  * @returns The throttler object.
84
89
  */
85
90
  startVacuum(): this;
86
91
 
87
92
  /**
88
93
  * Stops the vacuum process.
89
- * The vacuum process removes keys that expired.
94
+ * The vacuum process removes expired keys.
90
95
  * @returns The throttler object.
91
96
  */
92
97
  stopVacuum(): this;
package/src/Throttler.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./Throttler.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import sleep from './sleep.js';
6
4
 
7
5
  export class Throttler {
@@ -57,6 +55,7 @@ export class Throttler {
57
55
  this.handle = setInterval(() => {
58
56
  this.vacuum();
59
57
  }, this.vacuumPeriod);
58
+ if (this.handle.unref) this.handle.unref();
60
59
  return this;
61
60
  }
62
61