timeout-flow 0.0.17 → 0.0.19

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.
Files changed (49) hide show
  1. package/ADDITIONAL_TERMS.md +122 -0
  2. package/LICENSE +694 -0
  3. package/README.md +307 -237
  4. package/dist/timeout-flow.min.js +1 -6
  5. package/package.json +68 -58
  6. package/robots.txt +79 -3
  7. package/src/AfterTimer.js +82 -21
  8. package/src/EveryTimer.js +209 -88
  9. package/src/TimeoutFlow.js +400 -227
  10. package/src/TimerBase.js +133 -75
  11. package/src/abort.js +75 -0
  12. package/src/after.js +32 -83
  13. package/src/debounce.js +106 -40
  14. package/src/every.js +34 -120
  15. package/src/index.js +24 -19
  16. package/src/now.js +23 -0
  17. package/src/parseDuration.js +46 -44
  18. package/src/raf/ReadMe-Raf.md +94 -94
  19. package/src/raf/afterRaf.js +204 -72
  20. package/src/raf/debounceRaf.js +127 -45
  21. package/src/raf/everyRaf.js +317 -106
  22. package/src/raf/index.js +28 -8
  23. package/src/raf/throttleRaf.js +182 -38
  24. package/src/raf/waitForRaf.js +101 -33
  25. package/src/resolveDelayAndFn.js +90 -28
  26. package/src/retry.js +164 -24
  27. package/src/throttle.js +141 -47
  28. package/src/waitFor.js +77 -33
  29. package/types/AfterTimer.d.ts +8 -2
  30. package/types/EveryTimer.d.ts +21 -4
  31. package/types/TimeoutFlow.d.ts +6 -18
  32. package/types/TimerBase.d.ts +15 -4
  33. package/types/abort.d.ts +31 -0
  34. package/types/after.d.ts +22 -22
  35. package/types/debounce.d.ts +28 -6
  36. package/types/every.d.ts +20 -28
  37. package/types/index.d.ts +1 -1
  38. package/types/now.d.ts +1 -0
  39. package/types/raf/afterRaf.d.ts +35 -5
  40. package/types/raf/debounceRaf.d.ts +27 -6
  41. package/types/raf/everyRaf.d.ts +39 -9
  42. package/types/raf/index.d.ts +6 -5
  43. package/types/raf/throttleRaf.d.ts +33 -10
  44. package/types/raf/waitForRaf.d.ts +10 -4
  45. package/types/resolveDelayAndFn.d.ts +27 -0
  46. package/types/retry.d.ts +25 -8
  47. package/types/throttle.d.ts +28 -6
  48. package/types/waitFor.d.ts +11 -6
  49. package/LICENSE.MD +0 -285
package/src/TimerBase.js CHANGED
@@ -1,75 +1,133 @@
1
- // ./src/TimerBase.js
2
- import { parseDuration } from './parseDuration.js';
3
-
4
- /**
5
- * Base timer class to manage pause/resume/cancel behavior.
6
- * Not meant to be used directly—subclass for concrete behavior.
7
- */
8
- export class TimerBase {
9
- #ms;
10
- #startTime = null;
11
- #remaining;
12
- #timer = null;
13
- #running = false;
14
-
15
- /**
16
- * @param {string|number} duration - The duration to wait in ms or shorthand format
17
- */
18
- constructor(duration) {
19
- this.#ms = parseDuration(duration);
20
- this.#remaining = this.#ms;
21
- }
22
-
23
- /**
24
- * Whether the timer is currently running.
25
- * @returns {boolean}
26
- */
27
- get isRunning() {
28
- return this.#running;
29
- }
30
-
31
- /**
32
- * Pause the active timer, storing remaining time.
33
- */
34
- pause() {
35
- if (this.#running) {
36
- clearTimeout(this.#timer);
37
- this.#remaining -= Date.now() - this.#startTime;
38
- this.#running = false;
39
- }
40
- }
41
-
42
- /**
43
- * Resume the timer using the remaining time.
44
- * @param {Function} callback - Called when time completes
45
- * @param {number|null} [overrideDelay] - Optional custom delay in ms
46
- */
47
- resume(callback, overrideDelay = null) {
48
- if (!this.#running && this.#remaining > 0) {
49
- this.#startTime = Date.now();
50
- this.#running = true;
51
- this.#timer = setTimeout(() => {
52
- this.#running = false;
53
- callback?.();
54
- }, overrideDelay ?? this.#remaining);
55
- }
56
- }
57
-
58
- /**
59
- * Cancel the timer immediately.
60
- */
61
- cancel() {
62
- clearTimeout(this.#timer);
63
- this.#running = false;
64
- this.#timer = null;
65
- }
66
-
67
- /**
68
- * Reset the timer to its original delay, cancelling if needed.
69
- */
70
- reset() {
71
- this.cancel();
72
- this.#remaining = this.#ms;
73
- }
74
- }
75
-
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
+ }
133
+ }
package/src/abort.js ADDED
@@ -0,0 +1,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
+ }
package/src/after.js CHANGED
@@ -1,84 +1,33 @@
1
- // ./src/after.js
2
- import { parseDuration } from './parseDuration.js';
3
-
4
- import { AfterTimer } from './AfterTimer.js';
5
-
6
- /**
7
- * Schedules a one-time delayed function.
8
- *
9
- * @param {string|number} duration - e.g. '1s', 500, '2m'
10
- * @param {Function} fn - Main function to run
11
- * @param {Function} [onFinish] - Optional post-run callback
12
- * @returns {{
13
- * pause(): void,
14
- * resume(): void,
15
- * cancel(): void,
16
- * isRunning: boolean
17
- * }}
18
- */
19
- export function after(duration, fn, onFinish) {
20
- return new AfterTimer(duration, fn, onFinish);
21
- }
22
-
23
-
24
- /**
25
- * Schedules a one-time delayed function.
26
- * @param {string} duration - e.g. "5s", "500ms", "2m"
27
- * @param {Function} fn - callback to run
28
- * @returns {{
29
- * pause(): void,
30
- * resume(): void,
31
- * cancel(): void,
32
- * readonly isRunning: boolean,
33
- * }}
34
- */
35
- export function _after(duration, fn, onFinish) {
36
- const ms = parseDuration(duration);
37
- let startTime = Date.now();
38
- let remaining = ms;
39
- let running = true;
40
- let timer = null;
41
-
42
- const schedule = () => {
43
- startTime = Date.now();
44
- timer = setTimeout(() => {
45
- running = false;
46
- fn?.(); // Main Func to exec after delay.
47
- onFinish?.(); // Callback after running, if passed.
48
- }, remaining);
49
- };
50
-
51
-
52
- const pause = () => {
53
- if (running) {
54
- clearTimeout(timer);
55
- remaining -= Date.now() - startTime;
56
- running = false;
57
- }
58
- };
59
-
60
- const resume = () => {
61
- if (!running && remaining > 0) {
62
- startTime = Date.now();
63
- running = true;
64
- schedule();
65
- }
66
- };
67
-
68
- const cancel = () => {
69
- clearTimeout(timer);
70
- running = false;
71
- timer = null;
72
- };
73
-
74
- // Scedule Timer for execution.
75
- schedule();
76
-
77
- return {
78
- pause,
79
- resume,
80
- cancel,
81
- get isRunning() { return running; }
82
- };
83
-
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);
84
33
  }
package/src/debounce.js CHANGED
@@ -1,40 +1,106 @@
1
-
2
- // ./src/debounce.js
3
-
4
- import { resolveDelayAndFn } from './resolveDelayAndFn.js';
5
-
6
-
7
- /**
8
- * @typedef {((...args: any[]) => void) & { cancel: () => void }} DebouncedFunction
9
- */
10
-
11
-
12
- /**
13
- * Creates a debounced function that delays invoking `fn` until after `delay` ms.
14
- *
15
- * @param {string|number|Function} a - Delay in ms or the function to debounce.
16
- * @param {string|number|Function} [b] - The function to debounce, if delay is first
17
- * @returns {DebouncedFunction} A debounced function with `.cancel()`
18
- */
19
- export function debounce(a, b) {
20
- const { fn, delay } = resolveDelayAndFn(a, b);
21
- let timeoutId = null;
22
-
23
- /**
24
- * @param {...any[]} args
25
- */
26
- const debounced = function (...args) {
27
- clearTimeout(timeoutId);
28
- timeoutId = setTimeout(() => fn.apply(this, args), delay);
29
- };
30
-
31
- /**
32
- * Cancel any pending invocation
33
- */
34
- debounced.cancel = () => {
35
- clearTimeout(timeoutId);
36
- timeoutId = null;
37
- };
38
-
39
- return debounced;
40
- }
1
+ // ./src/debounce.js
2
+
3
+ import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
4
+ import { pendingAbort } from './abort.js';
5
+
6
+ /**
7
+ * @typedef {((...args: any[]) => void) & {
8
+ * cancel: () => void,
9
+ * flush: () => void
10
+ * }} DebouncedFunction
11
+ */
12
+
13
+ /**
14
+ * Creates a debounced function that delays invoking `fn`
15
+ * until after `delay` ms of inactivity.
16
+ *
17
+ * Preferred:
18
+ * - debounce(fn, [delay], [options]) // delay defaults to 0
19
+ *
20
+ * Also supported:
21
+ * - debounce(delay, fn, [options]) // legacy/alt ordering
22
+ * - debounce(fn, [options])
23
+ *
24
+ * Notes:
25
+ * - Always invokes with the latest arguments/context.
26
+ * - `.cancel()` clears any pending invocation.
27
+ * - `.flush()` immediately invokes if pending.
28
+ * - Optional AbortSignal: abort cancels pending invocation.
29
+ *
30
+ * @param {Function|string|number} a - Function or delay (see overloads)
31
+ * @param {Function|string|number|Object} [b] - Delay, function, or options
32
+ * @param {Object} [c] - Options (3-arg form)
33
+ * @param {AbortSignal} [c.signal] - Optional AbortSignal to cancel pending work
34
+ * @returns {DebouncedFunction}
35
+ */
36
+ export function debounce(a, b, c) {
37
+ const { fn, delay, options } = resolveDelayFnOptions(a, b, c, 0);
38
+ const signal = options?.signal;
39
+
40
+ const wait = Math.max(0, delay);
41
+
42
+ let timeoutId = 0;
43
+
44
+ /** @type {any[] | null} */
45
+ let lastArgs = null;
46
+ /** @type {any | null} */
47
+ let lastThis = null;
48
+
49
+ const abort = pendingAbort(signal, () => cancel());
50
+
51
+ const invoke = () => {
52
+ if (!lastArgs) return;
53
+
54
+ const args = lastArgs;
55
+ const ctx = lastThis;
56
+
57
+ // clear first (re-entrancy safe + GC friendly)
58
+ lastArgs = null;
59
+ lastThis = null;
60
+
61
+ abort.remove();
62
+ fn.apply(ctx, args);
63
+ };
64
+
65
+ const cancel = () => {
66
+ if (timeoutId) clearTimeout(timeoutId);
67
+ timeoutId = 0;
68
+
69
+ lastArgs = null;
70
+ lastThis = null;
71
+
72
+ abort.remove();
73
+ };
74
+
75
+ /** @type {any} */
76
+ const debounced = function (...args) {
77
+ if (signal?.aborted) return;
78
+
79
+ lastArgs = args;
80
+ lastThis = this;
81
+
82
+ if (timeoutId) clearTimeout(timeoutId);
83
+
84
+ // Listener should exist only while a call is pending
85
+ abort.add();
86
+
87
+ timeoutId = setTimeout(() => {
88
+ timeoutId = 0;
89
+ invoke();
90
+ }, wait);
91
+ };
92
+
93
+ debounced.cancel = cancel;
94
+
95
+ debounced.flush = () => {
96
+ if (!timeoutId) return;
97
+ clearTimeout(timeoutId);
98
+ timeoutId = 0;
99
+ invoke();
100
+ };
101
+
102
+ // If already aborted at creation time, ensure clean slate.
103
+ if (signal?.aborted) cancel();
104
+
105
+ return debounced;
106
+ }