timeout-flow 0.0.19 → 0.1.0

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/src/TimerBase.js CHANGED
@@ -1,133 +1,138 @@
1
- // ./src/TimerBase.js
2
- import { parseDuration } from './parseDuration.js';
3
- import { now } from './now.js'
4
-
5
-
6
- /**
7
- * Base timer class to manage pause/resume/cancel behavior.
8
- * Not meant to be used directly—subclass for concrete behavior.
9
- */
10
- export class TimerBase {
11
- #ms;
12
- #startTime = null; // performance.now()
13
- #remaining;
14
- #timer = null;
15
-
16
- #running = false;
17
- #paused = false;
18
- #finished = false;
19
-
20
- /**
21
- * @param {string|number} duration - The duration to wait in ms or shorthand format
22
- */
23
- constructor(duration) {
24
- this.#ms = parseDuration(duration);
25
- this.#remaining = this.#ms;
26
- }
27
-
28
- /**
29
- * Whether the timer is currently running (actively counting down).
30
- * @returns {boolean}
31
- */
32
- get isRunning() {
33
- return this.#running;
34
- }
35
-
36
- /**
37
- * Whether the timer is paused (resumable).
38
- * @returns {boolean}
39
- */
40
- get isPaused() {
41
- return this.#paused;
42
- }
43
-
44
- /**
45
- * Whether the timer has finished or been canceled (terminal state).
46
- * @returns {boolean}
47
- */
48
- get isFinished() {
49
- return this.#finished;
50
- }
51
-
52
- /**
53
- * Pause the active timer, storing remaining time.
54
- */
55
- pause() {
56
- if (!this.#running) return;
57
-
58
- clearTimeout(this.#timer);
59
- this.#timer = null;
60
-
61
- const elapsed = now() - this.#startTime;
62
- this.#remaining = Math.max(0, this.#remaining - elapsed);
63
-
64
- this.#running = false;
65
- this.#paused = true;
66
- // not finished; still resumable
67
- }
68
-
69
- /**
70
- * Resume the timer using the remaining time (or an override delay).
71
- * @param {Function} callback - Called when time completes
72
- * @param {number|null} [overrideDelay=null] - Optional custom delay in ms
73
- */
74
- resume(callback, overrideDelay = null) {
75
- if (this.#finished) return;
76
- if (this.#running) return;
77
-
78
- const rawDelay = overrideDelay ?? this.#remaining;
79
-
80
- // Reject invalid delays (avoid scheduling with NaN/Infinity/etc.)
81
- if (!Number.isFinite(rawDelay) || rawDelay < 0) return;
82
-
83
- // Support 0ms timers (schedule next macrotask)
84
- const delay = Math.max(0, rawDelay);
85
-
86
- // Important: remaining must reflect what we actually scheduled,
87
- // otherwise pause() math will be wrong when overrideDelay is used.
88
- this.#remaining = delay;
89
-
90
- this.#startTime = now();
91
- this.#running = true;
92
- this.#paused = false;
93
-
94
- this.#timer = setTimeout(() => {
95
- this.#timer = null;
96
- this.#running = false;
97
- this.#paused = false;
98
- this.#finished = true;
99
- this.#remaining = 0;
100
- callback?.();
101
- }, delay);
102
- }
103
-
104
- /**
105
- * Cancel the timer immediately (terminal).
106
- */
107
- cancel() {
108
- if (this.#timer) clearTimeout(this.#timer);
109
- this.#timer = null;
110
-
111
- this.#running = false;
112
- this.#paused = false;
113
- this.#finished = true;
114
- // leave #remaining as-is or set to 0; prefer 0 for "terminal means done"
115
- this.#remaining = 0;
116
- }
117
-
118
- /**
119
- * Reset the timer to its original delay, cancelling if needed.
120
- * After reset, the timer is not running.
121
- */
122
- reset() {
123
- if (this.#timer) clearTimeout(this.#timer);
124
- this.#timer = null;
125
-
126
- this.#startTime = null;
127
- this.#remaining = this.#ms;
128
-
129
- this.#running = false;
130
- this.#paused = false;
131
- this.#finished = false;
132
- }
1
+ // ./src/TimerBase.js
2
+ import { parseDuration } from './parseDuration.js';
3
+ import { now } from './now.js'
4
+
5
+
6
+ /**
7
+ * Base timer class to manage pause/resume/cancel behavior.
8
+ * Not meant to be used directly—subclass for concrete behavior.
9
+ */
10
+ export class TimerBase {
11
+ #ms;
12
+ #startTime = null; // performance.now()
13
+ #remaining;
14
+ #timer = null;
15
+ #callback;
16
+
17
+ #running = false;
18
+ #paused = false;
19
+ #finished = false;
20
+
21
+ /**
22
+ * @param {string|number} duration - The duration to wait in ms or shorthand format
23
+ */
24
+ constructor(duration) {
25
+ this.#ms = parseDuration(duration);
26
+ this.#remaining = this.#ms;
27
+ }
28
+
29
+ /**
30
+ * Whether the timer is currently running (actively counting down).
31
+ * @returns {boolean}
32
+ */
33
+ get isRunning() {
34
+ return this.#running;
35
+ }
36
+
37
+ /**
38
+ * Whether the timer is paused (resumable).
39
+ * @returns {boolean}
40
+ */
41
+ get isPaused() {
42
+ return this.#paused;
43
+ }
44
+
45
+ /**
46
+ * Whether the timer has finished or been canceled (terminal state).
47
+ * @returns {boolean}
48
+ */
49
+ get isFinished() {
50
+ return this.#finished;
51
+ }
52
+
53
+ /**
54
+ * Pause the active timer, storing remaining time.
55
+ */
56
+ pause() {
57
+ if (!this.#running) return;
58
+
59
+ clearTimeout(this.#timer);
60
+ this.#timer = null;
61
+
62
+ const elapsed = now() - this.#startTime;
63
+ this.#remaining = Math.max(0, this.#remaining - elapsed);
64
+
65
+ this.#running = false;
66
+ this.#paused = true;
67
+ // not finished; still resumable
68
+ }
69
+
70
+ /**
71
+ * Resume the timer using the remaining time (or an override delay).
72
+ * @param {Function} [callback] - Called when time completes; defaults to the previous callback
73
+ * @param {number|null} [overrideDelay=null] - Optional custom delay in ms
74
+ */
75
+ resume(callback, overrideDelay = null) {
76
+ if (this.#finished) return;
77
+ if (this.#running) return;
78
+
79
+ const rawDelay = overrideDelay ?? this.#remaining;
80
+
81
+ // Reject invalid delays (avoid scheduling with NaN/Infinity/etc.)
82
+ if (!Number.isFinite(rawDelay)) return;
83
+
84
+ // Negative delays clamp to 0 like setTimeout (next macrotask)
85
+ // instead of silently never firing.
86
+ const delay = Math.max(0, rawDelay);
87
+
88
+ callback ??= this.#callback;
89
+ this.#callback = callback;
90
+
91
+ // Important: remaining must reflect what we actually scheduled,
92
+ // otherwise pause() math will be wrong when overrideDelay is used.
93
+ this.#remaining = delay;
94
+
95
+ this.#startTime = now();
96
+ this.#running = true;
97
+ this.#paused = false;
98
+
99
+ this.#timer = setTimeout(() => {
100
+ this.#timer = null;
101
+ this.#running = false;
102
+ this.#paused = false;
103
+ this.#finished = true;
104
+ this.#remaining = 0;
105
+ callback?.();
106
+ }, delay);
107
+ }
108
+
109
+ /**
110
+ * Cancel the timer immediately (terminal).
111
+ */
112
+ cancel() {
113
+ if (this.#timer) clearTimeout(this.#timer);
114
+ this.#timer = null;
115
+
116
+ this.#running = false;
117
+ this.#paused = false;
118
+ this.#finished = true;
119
+ // leave #remaining as-is or set to 0; prefer 0 for "terminal means done"
120
+ this.#remaining = 0;
121
+ }
122
+
123
+ /**
124
+ * Reset the timer to its original delay, cancelling if needed.
125
+ * After reset, the timer is not running.
126
+ */
127
+ reset() {
128
+ if (this.#timer) clearTimeout(this.#timer);
129
+ this.#timer = null;
130
+
131
+ this.#startTime = null;
132
+ this.#remaining = this.#ms;
133
+
134
+ this.#running = false;
135
+ this.#paused = false;
136
+ this.#finished = false;
137
+ }
133
138
  }
package/src/abort.js CHANGED
@@ -1,75 +1,87 @@
1
- // ./src/abort.js
2
-
3
-
4
-
5
-
6
- /**
7
- * Standardized AbortError factory.
8
- * Works in browsers and Node runtimes that may not have DOMException.
9
- *
10
- * We resolve the best implementation once at module load time.
11
- * This avoids feature detection in the hot path.
12
- */
13
-
14
- let createAbortError;
15
-
16
- // Prefer native DOMException when available (browser + modern Node).
17
- if (typeof DOMException !== 'undefined') {
18
- createAbortError = (message = 'Aborted') =>
19
- new DOMException(message, 'AbortError');
20
- } else {
21
- // Fallback for runtimes without DOMException.
22
- createAbortError = (message = 'Aborted') => {
23
- const err = new Error(message);
24
- err.name = 'AbortError';
25
- return err;
26
- };
27
- }
28
-
29
- export { createAbortError };
30
- /**
31
- * Attach an AbortSignal listener and return a cleanup function.
32
- * - If `signal` is missing, returns a no-op cleanup.
33
- * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
34
- *
35
- * @param {AbortSignal | null | undefined} signal
36
- * @param {() => void} onAbort
37
- * @returns {() => void} cleanup
38
- */
39
- export function attachAbort(signal, onAbort) {
40
- if (!signal) return () => { };
41
- if (signal.aborted) {
42
- onAbort();
43
- return () => { };
44
- }
45
- signal.addEventListener('abort', onAbort, { once: true });
46
- return () => signal.removeEventListener('abort', onAbort);
47
- }
48
-
49
- /**
50
- * Manage AbortSignal listener lifecycle for "pending work" cases.
51
- * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
52
- *
53
- * @param {AbortSignal | null | undefined} signal
54
- * @param {() => void} onAbort
55
- * @returns {{ add: () => void, remove: () => void, reset: () => void }}
56
- */
57
- export function pendingAbort(signal, onAbort) {
58
- let cleanup = null;
59
-
60
- return {
61
- add() {
62
- if (cleanup) return;
63
- cleanup = attachAbort(signal, onAbort);
64
- },
65
- remove() {
66
- if (!cleanup) return;
67
- cleanup();
68
- cleanup = null;
69
- },
70
- reset() {
71
- if (cleanup) cleanup();
72
- cleanup = null;
73
- },
74
- };
75
- }
1
+ // ./src/abort.js
2
+
3
+
4
+
5
+
6
+ /**
7
+ * Standardized AbortError factory.
8
+ * Works in browsers and Node runtimes that may not have DOMException.
9
+ *
10
+ * We resolve the best implementation once at module load time.
11
+ * This avoids feature detection in the hot path.
12
+ */
13
+
14
+ let createAbortError;
15
+
16
+ // Prefer native DOMException when available (browser + modern Node).
17
+ if (typeof DOMException !== 'undefined') {
18
+ createAbortError = (message = 'Aborted') =>
19
+ new DOMException(message, 'AbortError');
20
+ } else {
21
+ // Fallback for runtimes without DOMException.
22
+ createAbortError = (message = 'Aborted') => {
23
+ const err = new Error(message);
24
+ err.name = 'AbortError';
25
+ return err;
26
+ };
27
+ }
28
+
29
+ export { createAbortError };
30
+ /**
31
+ * Attach an AbortSignal listener and return a cleanup function.
32
+ * - If `signal` is missing, returns a no-op cleanup.
33
+ * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
34
+ *
35
+ * @param {AbortSignal | null | undefined} signal
36
+ * @param {() => void} onAbort
37
+ * @returns {() => void} cleanup
38
+ */
39
+ export function attachAbort(signal, onAbort) {
40
+ if (!signal) return () => { };
41
+ if (signal.aborted) {
42
+ onAbort();
43
+ return () => { };
44
+ }
45
+ signal.addEventListener('abort', onAbort, { once: true });
46
+ return () => signal.removeEventListener('abort', onAbort);
47
+ }
48
+
49
+ /**
50
+ * Manage AbortSignal listener lifecycle for "pending work" cases.
51
+ * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
52
+ *
53
+ * @param {AbortSignal | null | undefined} signal
54
+ * @param {() => void} onAbort
55
+ * @returns {{ add: () => void, remove: () => void, reset: () => void }}
56
+ */
57
+ export function pendingAbort(signal, onAbort) {
58
+ let cleanup = null;
59
+
60
+ return {
61
+ add() {
62
+ if (cleanup) return;
63
+ cleanup = attachAbort(signal, onAbort);
64
+ },
65
+ remove() {
66
+ if (!cleanup) return;
67
+ cleanup();
68
+ cleanup = null;
69
+ },
70
+ reset() {
71
+ if (cleanup) cleanup();
72
+ cleanup = null;
73
+ },
74
+ };
75
+ }
76
+
77
+ /**
78
+ * The error an aborted operation should reject with: the signal's own
79
+ * `reason` (what `fetch()` and other web APIs use), falling back to a
80
+ * standard AbortError for runtimes without `AbortSignal.reason`.
81
+ *
82
+ * @param {AbortSignal | null | undefined} signal
83
+ * @returns {any}
84
+ */
85
+ export function abortReason(signal) {
86
+ return signal?.reason ?? createAbortError();
87
+ }
package/src/after.js CHANGED
@@ -1,33 +1,33 @@
1
- // ./src/after.js
2
- import { AfterTimer } from './AfterTimer.js';
3
- import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
4
-
5
- /**
6
- * Schedules a one-time delayed function.
7
- *
8
- * Preferred:
9
- * - after(fn, duration, [options])
10
- *
11
- * Also supported (legacy/alt):
12
- * - after(duration, fn, [options])
13
- *
14
- * @param {Function|string|number} a - Function or duration (see overloads)
15
- * @param {Function|string|number|Object} b - Duration, function, or options
16
- * @param {Object} [c] - Options
17
- * @param {Function} [c.onFinish] - Optional callback after `fn` runs
18
- * @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
19
- * @returns {{
20
- * pause(): void,
21
- * resume(): void,
22
- * cancel(): void,
23
- * reset(): void,
24
- * readonly isRunning: boolean,
25
- * readonly isPaused: boolean,
26
- * readonly isFinished: boolean
27
- * }}
28
- */
29
- export function after(a, b, c) {
30
- // require explicit duration: defaultDelay = undefined
31
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
32
- return new AfterTimer(delay, fn, options);
1
+ // ./src/after.js
2
+ import { AfterTimer } from './AfterTimer.js';
3
+ import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
4
+
5
+ /**
6
+ * Schedules a one-time delayed function.
7
+ *
8
+ * Preferred:
9
+ * - after(fn, duration, [options])
10
+ *
11
+ * Also supported (legacy/alt):
12
+ * - after(duration, fn, [options])
13
+ *
14
+ * @param {Function|string|number} a - Function or duration (see overloads)
15
+ * @param {Function|string|number|Object} b - Duration, function, or options
16
+ * @param {Object} [c] - Options
17
+ * @param {Function} [c.onFinish] - Optional callback after `fn` runs
18
+ * @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
19
+ * @returns {{
20
+ * pause(): void,
21
+ * resume(): void,
22
+ * cancel(): void,
23
+ * reset(): void,
24
+ * readonly isRunning: boolean,
25
+ * readonly isPaused: boolean,
26
+ * readonly isFinished: boolean
27
+ * }}
28
+ */
29
+ export function after(a, b, c) {
30
+ // require explicit duration: defaultDelay = undefined
31
+ const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
32
+ return new AfterTimer(delay, fn, options);
33
33
  }