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/every.js CHANGED
@@ -1,121 +1,35 @@
1
-
2
- // ./src/every.js
3
- import { parseDuration } from './parseDuration.js';
4
-
5
- import { EveryTimer } from './EveryTimer.js';
6
-
7
- /**
8
- * Runs a function every N ms with optional execution limit.
9
- *
10
- * @param {string|number} duration - e.g. '500ms', 1000
11
- * @param {Function} fn - Function to execute
12
- * @param {number} [max=Infinity] - Max times to run
13
- * @param {boolean} [runImmediately=false] - Run immediately on first tick
14
- * @returns {{
15
- * pause(): void,
16
- * resume(): void,
17
- * cancel(): void,
18
- * reset(restart?: boolean): void,
19
- * readonly isRunning: boolean,
20
- * readonly count: number
21
- * }}
22
- */
23
- export function every(duration, fn, max = Infinity, runImmediately = false) {
24
- return new EveryTimer(duration, fn, max, runImmediately);
25
- }
26
-
27
-
28
-
29
- /**
30
- * Runs a function every N milliseconds with optional execution limit.
31
- * Returns control methods: pause, resume, cancel, reset, and status flags.
32
- *
33
- * @param {string|number} duration - e.g. "1s", "500ms", "2m" or raw ms
34
- * @param {Function} fn - function to execute
35
- * @param {number} [maxTimes] - optional number of times to run
36
- * @returns {{
37
- * pause(): void,
38
- * resume(): void,
39
- * cancel(): void,
40
- * reset(restart?: boolean): void,
41
- * readonly isRunning: boolean,
42
- * readonly count: number
43
- * }}
44
- */
45
- export function _every(duration, fn, maxTimes = Infinity, runImmediately = false) {
46
- const ms = parseDuration(duration);
47
- let startTime = null;
48
- let remaining = ms;
49
- let running = false;
50
- let timer = null;
51
-
52
- let count = 0;
53
-
54
- const tick = () => {
55
- if (count >= maxTimes) {
56
- cancel();
57
- return;
58
- }
59
- fn?.(); // Main Func to exec after delay.
60
- count++
61
- scheduleNext(); // keep going
62
- };
63
-
64
- const scheduleNext = () => {
65
- timer = setTimeout(tick, ms);
66
- startTime = Date.now();
67
- remaining = ms;
68
- running = true;
69
- };
70
-
71
- const pause = () => {
72
- if (running) {
73
- clearTimeout(timer);
74
- remaining -= Date.now() - startTime;
75
- running = false;
76
- }
77
- };
78
-
79
- const resume = () => {
80
- if (!running && count < maxTimes && remaining > 0) {
81
- timer = setTimeout(tick, remaining);
82
- startTime = Date.now();
83
- running = true;
84
- }
85
- };
86
-
87
- const cancel = () => {
88
- clearTimeout(timer);
89
- running = false;
90
- timer = null;
91
- };
92
-
93
- const reset = (restart = false) => {
94
- cancel();
95
- count = 0;
96
- remaining = ms;
97
- if (restart) start();
98
- };
99
-
100
- const start = () => {
101
- if (runImmediately) {
102
- tick();
103
- } else {
104
- scheduleNext();
105
- }
106
- };
107
-
108
-
109
- // Initial launch
110
- start();
111
-
112
- return {
113
- pause,
114
- resume,
115
- cancel,
116
- reset,
117
- get isRunning() { return running; },
118
- get count() { return count; }
119
- };
120
-
1
+ // ./src/every.js
2
+ import { EveryTimer } from './EveryTimer.js';
3
+ import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
4
+
5
+ /**
6
+ * Runs a function every N ms with optional execution limit.
7
+ *
8
+ * Preferred:
9
+ * - every(fn, duration, [options])
10
+ *
11
+ * Also supported (legacy/alt):
12
+ * - every(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 {number} [c.max=Infinity] - Max times to run
18
+ * @param {boolean} [c.runImmediately=false] - Run immediately on first tick
19
+ * @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
20
+ * @returns {{
21
+ * pause(): void,
22
+ * resume(): void,
23
+ * cancel(): void,
24
+ * reset(restart?: boolean): void,
25
+ * readonly isRunning: boolean,
26
+ * readonly isPaused: boolean,
27
+ * readonly isFinished: boolean,
28
+ * readonly count: number
29
+ * }}
30
+ */
31
+ export function every(a, b, c) {
32
+ // require explicit duration: defaultDelay = undefined
33
+ const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
34
+ return new EveryTimer(delay, fn, options);
121
35
  }
package/src/index.js CHANGED
@@ -1,19 +1,24 @@
1
- // ./src/index.js
2
-
3
- export { parseDuration } from './parseDuration.js';
4
-
5
- export { flow } from './TimeoutFlow.js';
6
-
7
- export { throttle } from './throttle.js';
8
- export { debounce } from './debounce.js';
9
-
10
- export { after } from './after.js';
11
- export { every } from './every.js';
12
-
13
-
14
- export { waitFor } from './waitFor.js';
15
- export { retry } from './retry.js';
16
-
17
-
18
- // Add this line:
19
- export * from './raf/index.js';
1
+ // ./src/index.js
2
+
3
+ export { parseDuration } from './parseDuration.js';
4
+
5
+ export { flow } from './TimeoutFlow.js';
6
+
7
+ export { throttle } from './throttle.js';
8
+ export { debounce } from './debounce.js';
9
+
10
+ export { after } from './after.js';
11
+ export { every } from './every.js';
12
+
13
+
14
+ export { waitFor } from './waitFor.js';
15
+ export { retry } from './retry.js';
16
+
17
+
18
+ export {
19
+ afterRaf,
20
+ everyRaf,
21
+ debounceRaf,
22
+ throttleRaf,
23
+ waitForRaf
24
+ } from './raf/index.js';
package/src/now.js ADDED
@@ -0,0 +1,23 @@
1
+ // ./src/now.js
2
+
3
+ // We resolve the best available clock implementation *once* at module load time.
4
+ // This avoids doing feature detection on every call to `now()`,
5
+ // keeping the hot path branch-free and fast.
6
+
7
+ let now;
8
+
9
+ // Prefer high-resolution, monotonic clock when available.
10
+ // - Browsers: performance.now()
11
+ // - Modern Node: performance.now()
12
+ // This is ideal for measuring elapsed time.
13
+ if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
14
+ now = () => performance.now();
15
+ } else {
16
+ // Fallback for older Node or minimal runtimes.
17
+ // Date.now() is not monotonic, but ensures compatibility.
18
+ now = () => Date.now();
19
+ }
20
+
21
+ // Export the resolved implementation.
22
+ // Consumers simply call `now()` without worrying about environment differences.
23
+ export { now };
@@ -1,45 +1,47 @@
1
- // ./src/parseDuration.js
2
-
3
- // const timeMultipliers = Object.freeze({
4
- // "ms": 1,
5
- // "s": 1000,
6
- // "m": 60_000,
7
- // "h": 3_600_000,
8
- // });
9
-
10
- /** @const {!Object<string, number>} */
11
- const timeMultipliers = Object.freeze(JSON.parse(`{
12
- "ms": 1,
13
- "s": 1000,
14
- "m": 60000,
15
- "h": 3600000
16
- }`));
17
-
18
- /**
19
- * Parses a duration string like "2s", "1.5m", "500ms" into milliseconds.
20
- * Also accepts raw number values (treated as ms).
21
- * @param {string|number} input
22
- * @returns {number}
23
- */
24
- export function parseDuration(input) {
25
- if (typeof input === 'number' && Number.isFinite(input)) {
26
- return input;
27
- }
28
-
29
- if (typeof input !== 'string') {
30
- throw new TypeError(`Expected a duration string or number, got ${typeof input}`);
31
- }
32
-
33
- input = input.toLowerCase().trim();
34
-
35
- const match = input.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
36
-
37
- if (!match) {
38
- throw new Error(
39
- `Invalid duration format: "${input}". Expected formats like "500ms", "2s", "1.5m", or "1h".`
40
- );
41
- }
42
-
43
- const [, value, unit] = match;
44
- return parseFloat(value) * timeMultipliers[unit];
1
+ // ./src/parseDuration.js
2
+
3
+
4
+ /**
5
+ * Parses a duration string like "2s", "1.5m", "500ms" into milliseconds.
6
+ * Also accepts raw number values (treated as ms).
7
+ * @param {string|number} input
8
+ * @returns {number}
9
+ */
10
+ export function parseDuration(input) {
11
+ if (typeof input === 'number') {
12
+ if (!Number.isFinite(input)) {
13
+ throw new TypeError(`Expected a finite number of ms, got: ${input}`);
14
+ }
15
+ return input;
16
+ }
17
+
18
+ if (typeof input !== 'string') {
19
+ throw new TypeError(`Expected a duration string or number, got ${typeof input}`);
20
+ }
21
+
22
+ const str = input.toLowerCase().trim();
23
+ const match = str.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
24
+
25
+ if (!match) {
26
+ throw new Error(
27
+ `Invalid duration format: "${input}". Expected formats like "500ms", "2s", "1.5m", or "1h".`
28
+ );
29
+ }
30
+
31
+ const value = Number(match[1]);
32
+ if (!Number.isFinite(value)) {
33
+ throw new TypeError(`Invalid duration value: "${match[1]}"`);
34
+ }
35
+
36
+ const unit = match[2];
37
+
38
+ switch (unit) {
39
+ case 'ms': return value;
40
+ case 's': return value * 1000;
41
+ case 'm': return value * 60_000;
42
+ case 'h': return value * 3_600_000;
43
+ default:
44
+ // Should be unreachable due to regex, but keeps function total.
45
+ throw new Error(`Unsupported duration unit: "${unit}"`);
46
+ }
45
47
  }
@@ -1,94 +1,94 @@
1
- ## 🛯 Frame-Based Timing (RAF Utilities)
2
-
3
- These helpers use `requestAnimationFrame` under the hood to provide smooth, energy-efficient timing. Ideal for visual UI flows, canvas apps, scroll/resize behavior, and performance-sensitive interactions.
4
-
5
- All `raf` utilities automatically **pause in background tabs**, unlike timers.
6
-
7
- ---
8
-
9
- ### 👉 API Summary
10
-
11
- | Function | Purpose | Best For |
12
- |-------------------------|-------------------------------------------------------------------------|------------------------------------------------|
13
- | `afterRaf()` | Runs a function **once after N ms**, using `requestAnimationFrame`. | Idle effects, UI post-load, paint batching |
14
- | `everyRaf()` | Repeats a function **every N ms**, throttled via frames. | Sanity loops, smooth polling, visual checks |
15
- | `debounceRaf()` | Debounces a function using **frames instead of timeouts**. | Drag/move handlers, visual updates |
16
- | `debounceRaf('300ms', fn)` | Debounces like traditional debounce, but frame-aware. | Resize events, paused background flows |
17
- | `throttleRaf()` | Throttles execution to **at most once per frame**. | Scroll events, pointermove, paint-heavy flows |
18
- | `throttleRaf(fn, 2)` | Throttles to once every 3 frames (`frameSkip = 2`). | Advanced visuals, slower sync without timers |
19
- | `waitForRaf()` | Waits for a condition to become true using a frame-based loop. | DOM readiness, layout stability, visibility checks |
20
-
21
- ---
22
-
23
- ### ✨ Key Advantages
24
-
25
- - 🔄 **Frame-sync**: Triggered in sync with visual updates (60Hz or higher)
26
- - 🛌 **Background-tab safe**: No CPU use when inactive
27
- - ⚡ **Energy efficient**: Great for battery-conscious apps
28
- - 🧘 **Smoother UX**: Especially under load or heavy visuals
29
-
30
- ---
31
-
32
- ### 🛠 Example Usage
33
-
34
- ```js
35
- import { debounceRaf } from './raf/debounceRaf.js';
36
-
37
- // Wait 1 frame after rapid calls
38
- const onMouseMove = debounceRaf(() => {
39
- drawPreview();
40
- });
41
-
42
- // Wait 250ms of inactivity (with frame-based throttle)
43
- const onResize = debounceRaf('250ms', () => {
44
- updateLayout();
45
- });
46
- ```
47
-
48
- ```js
49
- import { afterRaf } from './raf/afterRaf.js';
50
-
51
- afterRaf('2s', () => {
52
- showIntroAnimation();
53
- });
54
- ```
55
-
56
- ```js
57
- import { everyRaf } from './raf/everyRaf.js';
58
-
59
- const loop = everyRaf('1s', () => {
60
- console.log('heartbeat');
61
- });
62
- ```
63
-
64
- ```js
65
- import { throttleRaf } from './raf/throttleRaf.js';
66
-
67
- // Throttle a scroll event to at most once per animation frame
68
- const onScroll = throttleRaf((e) => {
69
- handleScroll(e);
70
- });
71
-
72
- // Throttle to once every 3 frames (skip 2 frames)
73
- const onDrag = throttleRaf(drawFrame, 2);
74
- ```
75
-
76
- ```js
77
- import { waitForRaf } from './raf/waitForRaf.js';
78
-
79
- // Wait for an element to become visible or stable
80
- await waitForRaf(() => document.querySelector('#panel')?.offsetHeight > 0);
81
- ```
82
-
83
- ---
84
-
85
- ### 📦 File Locations
86
-
87
- | File | Description |
88
- |-----------------------|---------------------------------------------------------|
89
- | `raf/afterRaf.js` | One-time timer with frame pause support |
90
- | `raf/everyRaf.js` | Interval timer using `requestAnimationFrame` |
91
- | `raf/debounceRaf.js` | Smart debounce with optional duration and frame pause |
92
- | `raf/throttleRaf.js` | Input-event throttle using frame-skip control |
93
- | `raf/waitForRaf.js` | Waits for truthy condition using passive frame polling |
94
-
1
+ ## 🛯 Frame-Based Timing (RAF Utilities)
2
+
3
+ These helpers use `requestAnimationFrame` under the hood to provide smooth, energy-efficient timing. Ideal for visual UI flows, canvas apps, scroll/resize behavior, and performance-sensitive interactions.
4
+
5
+ All `raf` utilities automatically **pause in background tabs**, unlike timers.
6
+
7
+ ---
8
+
9
+ ### 👉 API Summary
10
+
11
+ | Function | Purpose | Best For |
12
+ |-------------------------|-------------------------------------------------------------------------|------------------------------------------------|
13
+ | `afterRaf()` | Runs a function **once after N ms**, using `requestAnimationFrame`. | Idle effects, UI post-load, paint batching |
14
+ | `everyRaf()` | Repeats a function **every N ms**, throttled via frames. | Sanity loops, smooth polling, visual checks |
15
+ | `debounceRaf()` | Debounces a function using **frames instead of timeouts**. | Drag/move handlers, visual updates |
16
+ | `debounceRaf('300ms', fn)` | Debounces like traditional debounce, but frame-aware. | Resize events, paused background flows |
17
+ | `throttleRaf()` | Throttles execution to **at most once per frame**. | Scroll events, pointermove, paint-heavy flows |
18
+ | `throttleRaf(fn, 2)` | Throttles to once every 3 frames (`frameSkip = 2`). | Advanced visuals, slower sync without timers |
19
+ | `waitForRaf()` | Waits for a condition to become true using a frame-based loop. | DOM readiness, layout stability, visibility checks |
20
+
21
+ ---
22
+
23
+ ### ✨ Key Advantages
24
+
25
+ - 🔄 **Frame-sync**: Triggered in sync with visual updates (60Hz or higher)
26
+ - 🛌 **Background-tab safe**: No CPU use when inactive
27
+ - ⚡ **Energy efficient**: Great for battery-conscious apps
28
+ - 🧘 **Smoother UX**: Especially under load or heavy visuals
29
+
30
+ ---
31
+
32
+ ### 🛠 Example Usage
33
+
34
+ ```js
35
+ import { debounceRaf } from './raf/debounceRaf.js';
36
+
37
+ // Wait 1 frame after rapid calls
38
+ const onMouseMove = debounceRaf(() => {
39
+ drawPreview();
40
+ });
41
+
42
+ // Wait 250ms of inactivity (with frame-based throttle)
43
+ const onResize = debounceRaf('250ms', () => {
44
+ updateLayout();
45
+ });
46
+ ```
47
+
48
+ ```js
49
+ import { afterRaf } from './raf/afterRaf.js';
50
+
51
+ afterRaf('2s', () => {
52
+ showIntroAnimation();
53
+ });
54
+ ```
55
+
56
+ ```js
57
+ import { everyRaf } from './raf/everyRaf.js';
58
+
59
+ const loop = everyRaf('1s', () => {
60
+ console.log('heartbeat');
61
+ });
62
+ ```
63
+
64
+ ```js
65
+ import { throttleRaf } from './raf/throttleRaf.js';
66
+
67
+ // Throttle a scroll event to at most once per animation frame
68
+ const onScroll = throttleRaf((e) => {
69
+ handleScroll(e);
70
+ });
71
+
72
+ // Throttle to once every 3 frames (skip 2 frames)
73
+ const onDrag = throttleRaf(drawFrame, 2);
74
+ ```
75
+
76
+ ```js
77
+ import { waitForRaf } from './raf/waitForRaf.js';
78
+
79
+ // Wait for an element to become visible or stable
80
+ await waitForRaf(() => document.querySelector('#panel')?.offsetHeight > 0);
81
+ ```
82
+
83
+ ---
84
+
85
+ ### 📦 File Locations
86
+
87
+ | File | Description |
88
+ |-----------------------|---------------------------------------------------------|
89
+ | `raf/afterRaf.js` | One-time timer with frame pause support |
90
+ | `raf/everyRaf.js` | Interval timer using `requestAnimationFrame` |
91
+ | `raf/debounceRaf.js` | Smart debounce with optional duration and frame pause |
92
+ | `raf/throttleRaf.js` | Input-event throttle using frame-skip control |
93
+ | `raf/waitForRaf.js` | Waits for truthy condition using passive frame polling |
94
+