time-queues 1.3.0 → 1.3.2

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.
@@ -1,4 +1,4 @@
1
- import {ListQueue, Task} from './ListQueue';
1
+ import {ListQueue, Task} from './ListQueue.js';
2
2
 
3
3
  /**
4
4
  * A page state.
@@ -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(
@@ -82,7 +82,7 @@ export declare class PageWatcher extends ListQueue {
82
82
  */
83
83
  export declare const watchStates: (
84
84
  queue: ListQueue,
85
- resumeStatesList: PageState[] = ['active']
85
+ resumeStatesList?: PageState[]
86
86
  ) => (state: PageState) => void;
87
87
 
88
88
  /**
@@ -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
@@ -29,7 +27,6 @@ export class PageWatcher extends ListQueue {
29
27
  }
30
28
 
31
29
  pause() {
32
- this.paused = true;
33
30
  watchedEvents.forEach(type => removeEventListener(type, this, eventHandlerOptions));
34
31
  return super.pause();
35
32
  }
@@ -52,7 +49,10 @@ export class PageWatcher extends ListQueue {
52
49
  }
53
50
 
54
51
  clear() {
55
- this.list.clear();
52
+ while (!this.list.isEmpty) {
53
+ const task = this.list.popFront();
54
+ task.cancel();
55
+ }
56
56
  return this;
57
57
  }
58
58
 
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');
@@ -35,11 +33,13 @@ export class Retainer {
35
33
  await this.destroy(value);
36
34
  return this;
37
35
  }
38
- this.handle = setTimeout(async () => {
36
+ this.handle = setTimeout(() => {
39
37
  const value = this.value;
40
38
  this.value = null;
41
39
  this.handle = null;
42
- await this.destroy(value);
40
+ Promise.resolve()
41
+ .then(() => this.destroy(value))
42
+ .catch(() => {});
43
43
  }, this.retentionPeriod);
44
44
  return this;
45
45
  }
@@ -1,5 +1,5 @@
1
- import MicroTask from './MicroTask';
2
- import MicroTaskQueue from './MicroTaskQueue';
1
+ import MicroTask from './MicroTask.js';
2
+ import MicroTaskQueue from './MicroTaskQueue.js';
3
3
 
4
4
  /**
5
5
  * A task that will be executed at a later time by `Scheduler`.
@@ -8,7 +8,7 @@ export declare class Task extends MicroTask {
8
8
  /**
9
9
  * The function to execute.
10
10
  */
11
- fn: ({task: Task, scheduler: Scheduler}) => unknown;
11
+ fn: (arg: {task: Task; scheduler: Scheduler}) => unknown;
12
12
 
13
13
  /**
14
14
  * Whether the task has been canceled.
@@ -30,7 +30,7 @@ export declare class Task extends MicroTask {
30
30
  * @param delay The delay before the task is executed. It can be a number of milliseconds or a `Date` object as an absolute time.
31
31
  * @param fn The function to execute.
32
32
  */
33
- constructor(delay: number | Date, fn: ({task: Task, scheduler: Scheduler}) => unknown);
33
+ constructor(delay: number | Date, fn: (arg: {task: Task; scheduler: Scheduler}) => unknown);
34
34
 
35
35
  /**
36
36
  * Makes a promise that will be resolved when the microtask is executed.
@@ -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
 
@@ -101,23 +102,23 @@ export declare class Scheduler extends MicroTaskQueue {
101
102
  * @param delay The delay before the task is executed. It can be a number of milliseconds or a `Date` object as an absolute time.
102
103
  * @returns The task object that was enqueued.
103
104
  */
104
- enqueue(fn: ({task: Task, scheduler: Scheduler}) => unknown, delay: number | Date): Task;
105
+ enqueue(fn: (arg: {task: Task; scheduler: Scheduler}) => unknown, delay: number | Date): Task;
105
106
 
106
107
  /**
107
108
  * Removes a task from the scheduler.
108
109
  * @param task The task to remove.
109
110
  * @returns The scheduler object for chaining.
110
111
  */
111
- dequeue(task: Task): this;
112
+ dequeue(task: MicroTask): this;
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
  */
119
120
  schedule(
120
- fn: (({task: Task, scheduler: Scheduler}) => unknown) | null | undefined,
121
+ fn: ((arg: {task: Task; scheduler: Scheduler}) => unknown) | null | undefined,
121
122
  delay: number | Date
122
123
  ): Task;
123
124
 
@@ -149,9 +150,9 @@ export declare class Scheduler extends MicroTaskQueue {
149
150
  * @returns A function that can be used to enqueue the task to the scheduler.
150
151
  */
151
152
  export declare const repeat: (
152
- fn: ({task: Task, scheduler: Scheduler}) => void,
153
+ fn: (arg: {task: Task; scheduler: Scheduler}) => void,
153
154
  delay: number | Date
154
- ) => ({task: Task, scheduler: Scheduler}) => void;
155
+ ) => (arg: {task: Task; scheduler: Scheduler}) => void;
155
156
 
156
157
  /**
157
158
  * A scheduler instance usually used as a global scheduler.
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';
@@ -72,6 +70,7 @@ export class Scheduler extends MicroTaskQueue {
72
70
  dequeue(task) {
73
71
  task.cancel();
74
72
  if (this.queue.isEmpty) return this;
73
+ if (!this.queue.has(task)) return this;
75
74
  if (this.paused || this.queue.top !== task) {
76
75
  this.queue.remove(task);
77
76
  return this;
@@ -90,6 +89,7 @@ export class Scheduler extends MicroTaskQueue {
90
89
  this.queue.array.forEach(task => task.cancel());
91
90
  this.queue.clear();
92
91
  if (!paused) this.resume();
92
+ return this;
93
93
  }
94
94
 
95
95
  startQueue() {
@@ -109,6 +109,7 @@ export class Scheduler extends MicroTaskQueue {
109
109
  this.queue.top.time <= Date.now() + this.tolerance
110
110
  ) {
111
111
  const task = this.queue.pop();
112
+ if (task.isCanceled) continue;
112
113
  task.fn({task, scheduler: this});
113
114
  }
114
115
 
@@ -119,7 +120,7 @@ export class Scheduler extends MicroTaskQueue {
119
120
  export const repeat = (fn, delay) => {
120
121
  const repeatableFunction = ({task, scheduler}) => {
121
122
  fn({task, scheduler});
122
- scheduler.enqueue(repeatableFunction, isNaN(delay) ? task.delay : delay);
123
+ if (!task.isCanceled) scheduler.enqueue(repeatableFunction, isNaN(delay) ? task.delay : delay);
123
124
  };
124
125
  return repeatableFunction;
125
126
  };
@@ -44,11 +44,7 @@ export declare class Throttler implements ThrottlerOptions {
44
44
  * Creates a new throttler.
45
45
  * @param options The options for the throttler.
46
46
  */
47
- constructor({
48
- throttleTimeout = 1_000,
49
- neverSeenTimeout = 0,
50
- vacuumPeriod = throttleTimeout * 3
51
- }: ThrottlerOptions = {});
47
+ constructor(options?: ThrottlerOptions);
52
48
 
53
49
  /**
54
50
  * Retrieves the last seen time for a key as a timestamp in milliseconds.
@@ -71,6 +67,11 @@ export declare class Throttler implements ThrottlerOptions {
71
67
  */
72
68
  wait(key: unknown): Promise<void>;
73
69
 
70
+ /**
71
+ * Removes expired keys from the last seen map.
72
+ */
73
+ vacuum(): void;
74
+
74
75
  /**
75
76
  * Retrieves the vacuuming state.
76
77
  * @returns `true` if the vacuuming is active, `false` otherwise.
@@ -79,14 +80,14 @@ export declare class Throttler implements ThrottlerOptions {
79
80
 
80
81
  /**
81
82
  * Starts the vacuum process.
82
- * The vacuum process removes keys that expired.
83
+ * The vacuum process removes expired keys.
83
84
  * @returns The throttler object.
84
85
  */
85
86
  startVacuum(): this;
86
87
 
87
88
  /**
88
89
  * Stops the vacuum process.
89
- * The vacuum process removes keys that expired.
90
+ * The vacuum process removes expired keys.
90
91
  * @returns The throttler object.
91
92
  */
92
93
  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
 
package/src/audit.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./audit.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export const audit = (fn, ms) => {
6
4
  let handle = null,
7
5
  lastSeenArgs = null;
package/src/batch.d.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Runs asynchronous operations in parallel, no more than a specified number at a time.
3
3
  * It takes an array of functions, which return promises when invoked without arguments.
4
4
  * All other non-function values are passed as-is and promises are resolved.
5
- * Modelled after Promise.all().
5
+ * Modeled after Promise.all().
6
6
  *
7
7
  * @param fns An array of parameterless functions (asynchronous or not), promises, or values
8
8
  * @param limit How many asynchronous operations to run in parallel (default is 4)
package/src/batch.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./batch.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  const wrap = value => {
6
4
  if (typeof value == 'function') return Promise.resolve(value());
7
5
  if (value && typeof value.then == 'function') return value; // thenable
@@ -9,6 +7,7 @@ const wrap = value => {
9
7
  };
10
8
 
11
9
  export const batch = (fns, limit = 4) => {
10
+ if (!fns.length) return Promise.resolve([]);
12
11
  if (limit < 1) limit = 1;
13
12
 
14
13
  const result = [];
package/src/debounce.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./debounce.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export const debounce = (fn, ms) => {
6
4
  let handle = null;
7
5
  return (...args) => {
package/src/defer.d.ts CHANGED
@@ -6,12 +6,11 @@
6
6
  * - `setTimeout()`
7
7
  *
8
8
  * @param fn The function to delay.
9
- * @returns A function that, when called, will execute the provided function.
10
9
  */
11
- export declare function defer<A extends unknown[]>(fn: (...args: A) => void): (...args: A) => void;
10
+ export declare function defer(fn: () => void): void;
12
11
 
13
12
  /**
14
- * Schedules a function to be called when the next available time.
13
+ * Schedules a function to be called at the next available time.
15
14
  *
16
15
  * @param fn The function to schedule.
17
16
  * @returns A promise that resolves when the function is called.
@@ -19,7 +18,7 @@ export declare function defer<A extends unknown[]>(fn: (...args: A) => void): (.
19
18
  export declare function scheduleDefer<R extends unknown>(fn: () => R): Promise<Awaited<R>>;
20
19
 
21
20
  /**
22
- * Schedules a function to be called when the next available time.
21
+ * Schedules a function to be called at the next available time.
23
22
  *
24
23
  * @param fn The function to schedule.
25
24
  * @returns A promise that resolves when the function is called.
package/src/defer.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./defer.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  let deferImplementation = setTimeout;
6
4
 
7
5
  if (typeof requestIdleCallback == 'function') {
package/src/index.d.ts CHANGED
@@ -1,24 +1,27 @@
1
- declare module 'time-queues' {
2
- export * from './audit';
3
- export * from './debounce';
4
- export * from './defer';
5
- export * from './sample';
6
- export * from './sleep';
7
- export * from './throttle';
1
+ export * from './audit.js';
2
+ export * from './batch.js';
3
+ export * from './debounce.js';
4
+ export * from './defer.js';
5
+ export * from './sample.js';
6
+ export * from './sleep.js';
7
+ export * from './throttle.js';
8
8
 
9
- export * from './CancelTaskError';
10
- export * from './MicroTask';
11
- export * from './MicroTaskQueue';
12
- export * from './ListQueue';
13
- export * from './FrameQueue';
14
- export * from './IdleQueue';
9
+ export * from './CancelTaskError.js';
10
+ export * from './MicroTask.js';
11
+ export * from './MicroTaskQueue.js';
12
+ export * from './LimitedQueue.js';
13
+ export * from './ListQueue.js';
14
+ export * from './FrameQueue.js';
15
+ export {IdleQueue, idleQueue} from './IdleQueue.js';
15
16
 
16
- export * from './PageWatcher';
17
- export * from './Scheduler';
18
- export * from './Retainer';
19
- export * from './Throttler';
20
- export * from './Counter';
17
+ export * from './Counter.js';
18
+ export * from './PageWatcher.js';
19
+ export * from './Retainer.js';
20
+ export {Task as SchedulerTask, Scheduler, repeat, scheduler} from './Scheduler.js';
21
+ export * from './Throttler.js';
21
22
 
22
- export * from './when-dom-loaded';
23
- export * from './when-loaded';
24
- }
23
+ export * from './random-dist.js';
24
+ export * from './random-sleep.js';
25
+
26
+ export * from './when-dom-loaded.js';
27
+ export {whenLoaded, scheduleWhenLoaded} from './when-loaded.js';
@@ -13,7 +13,7 @@ export declare function uniform(min: number, max: number): number;
13
13
  * @param skewness The skewness of the distribution.
14
14
  * @returns A random number from the normal distribution.
15
15
  */
16
- export declare function normal(mean: number, stdDev: number, skewness: number = 0): number;
16
+ export declare function normal(mean: number, stdDev: number, skewness?: number): number;
17
17
 
18
18
  /**
19
19
  * Generate a random number from an exponential distribution.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Random sleep function modelled after `sleep()`.
2
+ * Random sleep function modeled after `sleep()`.
3
3
  */
4
4
  export type RandomSleepFunction = () => Promise<void>;
5
5
 
@@ -21,7 +21,7 @@ export declare function randomUniformSleep(min: number, max: number): RandomSlee
21
21
  export declare function randomNormalSleep(
22
22
  mean: number,
23
23
  stdDev: number,
24
- skewness: number = 0
24
+ skewness?: number
25
25
  ): RandomSleepFunction;
26
26
 
27
27
  /**
@@ -34,7 +34,7 @@ export declare function randomNormalSleep(
34
34
  export declare function randomExpoSleep(
35
35
  rate: number,
36
36
  range: number,
37
- base: number = 0
37
+ base?: number
38
38
  ): RandomSleepFunction;
39
39
 
40
40
  /**
@@ -44,7 +44,7 @@ export declare function randomExpoSleep(
44
44
  * @returns A sleep function.
45
45
  * @throws Error if the ratio is not between 0.5 and 1.
46
46
  */
47
- export declare function randomParetoSleep(min: number, ratio: number = 0.8): RandomSleepFunction;
47
+ export declare function randomParetoSleep(min: number, ratio?: number): RandomSleepFunction;
48
48
 
49
49
  /**
50
50
  * A simple sleep function that uses a uniform distribution.
@@ -52,6 +52,6 @@ export declare function randomParetoSleep(min: number, ratio: number = 0.8): Ran
52
52
  * @param min The minimum delay in milliseconds.
53
53
  * @returns A promise that resolves after the delay.
54
54
  */
55
- export declare function randomSleep(max: number, min: number = 0): Promise<void>;
55
+ export declare function randomSleep(max: number, min?: number): Promise<void>;
56
56
 
57
57
  export default randomSleep;
package/src/sample.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Samples a function by ensuring it is not called more often than the specified interval.
3
3
  * The last seen arguments are passed to the function after the specified time interval.
4
- * Unlike `audit()`, intervals are not reset by the function calls and never stops.
4
+ * Unlike `audit()`, intervals are not reset by the function calls and never stop.
5
5
  * If no call was made to the sampled function within the specified time interval,
6
6
  * no calls are made after the specified time interval.
7
7
  *
package/src/sample.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./sample.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export const sample = (fn, ms) => {
6
4
  const started = Date.now();
7
5
  let handle = null,
package/src/sleep.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./sleep.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export const sleep = ms => {
6
4
  if (ms instanceof Date) {
7
5
  ms = ms.getTime() - Date.now();
package/src/throttle.js CHANGED
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./throttle.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  export const throttle = (fn, ms) => {
6
4
  let handle = null;
7
5
  return (...args) => {
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./when-dom-loaded.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import ValueList from 'list-toolkit/value-list.js';
6
4
 
7
5
  const waitingForDom = new ValueList();
@@ -1,7 +1,5 @@
1
1
  // @ts-self-types="./when-loaded.d.ts"
2
2
 
3
- 'use strict';
4
-
5
3
  import ValueList from 'list-toolkit/value-list.js';
6
4
 
7
5
  const waitingForLoad = new ValueList();