timeout-flow 0.0.17 → 0.0.18

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 (46) hide show
  1. package/README.md +239 -144
  2. package/dist/timeout-flow.min.js +1 -6
  3. package/package.json +2 -1
  4. package/src/AfterTimer.js +64 -3
  5. package/src/EveryTimer.js +139 -18
  6. package/src/TimeoutFlow.js +291 -118
  7. package/src/TimerBase.js +81 -23
  8. package/src/abort.js +75 -0
  9. package/src/after.js +20 -71
  10. package/src/context-js.bat +58 -0
  11. package/src/context.txt +2604 -0
  12. package/src/debounce.js +90 -24
  13. package/src/every.js +19 -105
  14. package/src/index.js +7 -2
  15. package/src/now.js +23 -0
  16. package/src/parseDuration.js +22 -20
  17. package/src/raf/afterRaf.js +198 -66
  18. package/src/raf/debounceRaf.js +108 -26
  19. package/src/raf/everyRaf.js +278 -67
  20. package/src/raf/index.js +26 -6
  21. package/src/raf/throttleRaf.js +175 -31
  22. package/src/raf/waitForRaf.js +82 -14
  23. package/src/resolveDelayAndFn.js +69 -7
  24. package/src/retry.js +152 -12
  25. package/src/throttle.js +120 -26
  26. package/src/waitFor.js +68 -24
  27. package/types/AfterTimer.d.ts +8 -2
  28. package/types/EveryTimer.d.ts +21 -4
  29. package/types/TimeoutFlow.d.ts +6 -18
  30. package/types/TimerBase.d.ts +15 -4
  31. package/types/abort.d.ts +31 -0
  32. package/types/after.d.ts +22 -22
  33. package/types/debounce.d.ts +28 -6
  34. package/types/every.d.ts +20 -28
  35. package/types/index.d.ts +1 -1
  36. package/types/now.d.ts +1 -0
  37. package/types/raf/afterRaf.d.ts +35 -5
  38. package/types/raf/debounceRaf.d.ts +27 -6
  39. package/types/raf/everyRaf.d.ts +39 -9
  40. package/types/raf/index.d.ts +6 -5
  41. package/types/raf/throttleRaf.d.ts +33 -10
  42. package/types/raf/waitForRaf.d.ts +10 -4
  43. package/types/resolveDelayAndFn.d.ts +27 -0
  44. package/types/retry.d.ts +25 -8
  45. package/types/throttle.d.ts +28 -6
  46. package/types/waitFor.d.ts +11 -6
@@ -1,45 +1,127 @@
1
1
  // ./raf/debounceRaf.js
2
-
3
- import { parseDuration } from '../parseDuration.js';
2
+ import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
3
+ import { pendingAbort } from '../abort.js';
4
+ import { now } from '../now.js';
4
5
 
5
6
  /**
6
7
  * Debounces a function using requestAnimationFrame.
7
- * - If no duration is passed, triggers on the next frame.
8
- * - If duration is passed, waits until N ms of inactivity using frame-based timing.
9
8
  *
10
- * @param {string|number|Function} durationOrFn - Duration (e.g., "300ms") or fn directly
11
- * @param {Function} [callbackFn] - Callback (if duration is passed as first arg)
12
- * @returns {Function} debounced function
9
+ * Preferred:
10
+ * - debounceRaf(fn, [duration], [options]) // duration defaults to 0 (next frame)
11
+ *
12
+ * Also supported:
13
+ * - debounceRaf(duration, fn, [options])
14
+ * - debounceRaf(fn, [options])
15
+ *
16
+ * Timing model:
17
+ * - Waits until `ms` of inactivity have passed (measured using frame timestamps).
18
+ * - `ms = 0` means "run on the next animation frame" (still debounced).
19
+ *
20
+ * Supports:
21
+ * - `.cancel()` clears any pending invocation.
22
+ * - `.flush()` immediately invokes if pending.
23
+ * - Optional AbortSignal: abort cancels any pending invocation.
24
+ *
25
+ * @param {Function|string|number} a - function or duration
26
+ * @param {Function|string|number|Object} [b] - duration, fn, or options
27
+ * @param {Object} [c] - options (3-arg form)
28
+ * @param {AbortSignal} [c.signal] - AbortSignal to auto-cancel pending work
29
+ * @returns {((...args: any[]) => void) & { cancel: () => void, flush: () => void }}
13
30
  */
14
- export function debounceRaf(durationOrFn, callbackFn) {
15
- const [ms, fn] =
16
- typeof durationOrFn === 'function'
17
- ? [0, durationOrFn] // ← next frame, no time threshold
18
- : [parseDuration(durationOrFn), callbackFn];
31
+ export function debounceRaf(a, b, c) {
32
+ // duration is optional for debounceRaf (defaults to 0)
33
+ const { fn, delay, options } = resolveDelayFnOptions(a, b, c, 0);
34
+
35
+ const ms = Math.max(0, delay);
36
+ const signal = options?.signal;
19
37
 
20
- let frame = null;
38
+ let rafId = 0;
39
+
40
+ /** @type {any[] | null} */
21
41
  let lastArgs = null;
42
+ /** @type {any | null} */
43
+ let lastThis = null;
44
+
45
+ // last time the debounced function was called (used for inactivity measurement)
22
46
  let lastCallTime = 0;
23
47
 
24
- const tick = (timestamp) => {
25
- const elapsed = timestamp - lastCallTime;
48
+ const clearRaf = () => {
49
+ if (rafId) cancelAnimationFrame(rafId);
50
+ rafId = 0;
51
+ };
52
+
53
+ const abort = pendingAbort(signal, () => cancel());
54
+
55
+ const cancel = () => {
56
+ clearRaf();
57
+ lastArgs = null;
58
+ lastThis = null;
59
+ lastCallTime = 0;
60
+ abort.remove();
61
+ };
62
+
63
+ const invoke = () => {
64
+ if (!lastArgs) return;
65
+
66
+ const args = lastArgs;
67
+ const ctx = lastThis;
68
+
69
+ // Clear first (re-entrancy safe + GC friendly)
70
+ lastArgs = null;
71
+ lastThis = null;
72
+
73
+ abort.remove();
74
+ fn.apply(ctx, args);
75
+ };
76
+
77
+ const tick = (ts) => {
78
+ if (!rafId) return; // canceled
79
+
80
+ if (!lastArgs) {
81
+ // Nothing pending; clean slate
82
+ cancel();
83
+ return;
84
+ }
85
+
86
+ const elapsed = ts - lastCallTime;
26
87
 
27
88
  if (elapsed >= ms) {
28
- fn(...lastArgs);
29
- frame = null;
30
- } else {
31
- frame = requestAnimationFrame(tick);
89
+ // Stop scheduling first, then invoke
90
+ clearRaf();
91
+ invoke();
92
+ return;
32
93
  }
94
+
95
+ rafId = requestAnimationFrame(tick);
33
96
  };
34
97
 
35
- return (...args) => {
98
+ /** @type {any} */
99
+ const debounced = function (...args) {
100
+ if (signal?.aborted) return;
101
+
36
102
  lastArgs = args;
37
- lastCallTime = performance.now();
103
+ lastThis = this;
38
104
 
39
- if (frame !== null) {
40
- cancelAnimationFrame(frame);
41
- }
105
+ // Use monotonic clock for call timestamp; RAF tick uses its own timestamp.
106
+ lastCallTime = now();
107
+
108
+ // Ensure abort listener exists only while pending work exists
109
+ abort.add();
42
110
 
43
- frame = requestAnimationFrame(tick);
111
+ clearRaf();
112
+ rafId = requestAnimationFrame(tick);
44
113
  };
45
- }
114
+
115
+ debounced.cancel = cancel;
116
+
117
+ debounced.flush = () => {
118
+ if (!rafId || !lastArgs) return;
119
+ clearRaf();
120
+ invoke();
121
+ };
122
+
123
+ // If already aborted at creation time, ensure clean slate.
124
+ if (signal?.aborted) cancel();
125
+
126
+ return debounced;
127
+ }
@@ -1,106 +1,317 @@
1
-
2
1
  // ./raf/everyRaf.js
2
+ import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
3
+ import { attachAbort } from '../abort.js';
4
+ import { now } from '../now.js';
3
5
 
4
- import { parseDuration } from '../parseDuration.js';
6
+ const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
5
7
 
6
8
  /**
7
- * Repeats a function every N milliseconds using requestAnimationFrame
8
- * (instead of setTimeout/setInterval).
9
- *
10
- * @param {string|number} duration - Interval duration ("1s", "500ms", 500, etc.)
11
- * @param {Function} fn - Function to run
12
- * @param {number} [maxTimes=Infinity] - Max number of executions
13
- * @param {boolean} [runImmediately=false] - Whether to run immediately
14
- * @returns {Object} - Control methods and flags
9
+ * Repeats a function every N milliseconds using requestAnimationFrame.
10
+ *
11
+ * Preferred:
12
+ * - everyRaf(fn, duration, [options])
13
+ *
14
+ * Also supported (legacy):
15
+ * - everyRaf(duration, fn, [maxTimes], [runImmediately], [options])
16
+ *
17
+ * Timing model:
18
+ * - Counts down using frame deltas.
19
+ * - Paused time does NOT count (pause freezes remaining-to-next-tick).
20
+ * - On large frame gaps, may "catch up" by running multiple ticks in one frame,
21
+ * but will never exceed max.
22
+ *
23
+ * @param {Function|string|number} a
24
+ * @param {Function|string|number|Object} b
25
+ * @param {number|boolean|Object} [c] - legacy maxTimes OR legacy runImmediately OR options
26
+ * @param {boolean|Object} [d] - legacy runImmediately OR options
27
+ * @param {Object} [e] - legacy options
28
+ * @returns {{
29
+ * pause(): void,
30
+ * resume(): void,
31
+ * cancel(): void,
32
+ * reset(restart?: boolean): void,
33
+ * readonly isRunning: boolean,
34
+ * readonly isPaused: boolean,
35
+ * readonly isFinished: boolean,
36
+ * readonly count: number
37
+ * }}
15
38
  */
16
- export function everyRaf(duration, fn, maxTimes = Infinity, runImmediately = false) {
17
- const ms = typeof duration === 'string' ? parseDuration(duration) : duration;
18
- let handle = null;
19
- let startTimestamp = null;
20
- let lastTimestamp = null;
39
+ export function everyRaf(a, b, c, d, e) {
40
+ const durationFirst = typeof a !== 'function';
41
+
42
+ // ---- Normalize legacy positional args into options (without breaking legacy behavior) ----
43
+ let legacyMax;
44
+ let legacyRunImmediately;
45
+
46
+ /** @type {any} */
47
+ let optionsCandidate;
48
+
49
+ if (durationFirst) {
50
+ // Legacy or duration-first:
51
+ // - everyRaf(duration, fn, options)
52
+ // - everyRaf(duration, fn, maxTimes, runImmediately, options)
53
+ // - everyRaf(duration, fn, maxTimes, options)
54
+ // - everyRaf(duration, fn, runImmediately, options) (extra leniency)
55
+ if (isPlainOptions(c)) {
56
+ optionsCandidate = c;
57
+ } else if (isPlainOptions(d)) {
58
+ optionsCandidate = d;
59
+ } else if (isPlainOptions(e)) {
60
+ optionsCandidate = e;
61
+ } else {
62
+ optionsCandidate = {};
63
+ }
64
+
65
+ if (typeof c === 'number') legacyMax = c;
66
+ if (typeof d === 'boolean') legacyRunImmediately = d;
67
+
68
+ // Lenient support: (duration, fn, true, options) => runImmediately=true
69
+ if (legacyRunImmediately == null && typeof c === 'boolean') legacyRunImmediately = c;
70
+ } else {
71
+ // Preferred fn-first:
72
+ // - everyRaf(fn, duration, options?)
73
+ optionsCandidate = isPlainOptions(c) ? c : {};
74
+ }
75
+
76
+ // Parse fn + duration using shared helper (duration is REQUIRED)
77
+ const { fn, delay, options } = resolveDelayFnOptions(a, b, optionsCandidate, undefined);
78
+
79
+ const signal = options?.signal;
80
+
81
+ const maxFromOptions = options?.max ?? Infinity;
82
+ const runImmediatelyFromOptions = options?.runImmediately ?? false;
83
+
84
+ // Legacy positional should win (to preserve prior behavior)
85
+ const max = legacyMax != null ? legacyMax : maxFromOptions;
86
+ const runImmediately =
87
+ legacyRunImmediately != null ? legacyRunImmediately : runImmediatelyFromOptions;
88
+
89
+ const intervalMs = Math.max(0, delay);
90
+
91
+ let rafId = 0;
92
+ let count = 0;
93
+
94
+ // remaining time until next tick (pause-safe)
95
+ let remainingToNext = intervalMs;
96
+
97
+ // last frame timestamp (used for delta while running)
98
+ let lastTs = null; // number | null
99
+
21
100
  let running = false;
22
101
  let paused = false;
23
- let elapsedWhilePaused = 0;
24
- let count = 0;
102
+ let finished = false;
25
103
 
26
- const tick = (timestamp) => {
27
- if (!running || paused) return;
104
+ const cancelFrame = () => {
105
+ if (rafId) cancelAnimationFrame(rafId);
106
+ rafId = 0;
107
+ };
28
108
 
29
- if (startTimestamp == null) {
30
- startTimestamp = timestamp;
31
- lastTimestamp = timestamp;
32
- }
109
+ let cleanupAbort = () => { };
110
+
111
+ const cleanupAbortListener = () => {
112
+ cleanupAbort();
113
+ cleanupAbort = () => { };
114
+ };
115
+
116
+ const finish = () => {
117
+ cancelFrame();
118
+ running = false;
119
+ paused = false;
120
+ finished = true;
33
121
 
34
- const elapsed = timestamp - lastTimestamp + elapsedWhilePaused;
122
+ lastTs = null;
123
+ remainingToNext = 0;
35
124
 
36
- if (elapsed >= ms) {
37
- if (count >= maxTimes) {
38
- cancel();
39
- return;
40
- }
41
- fn?.();
42
- count++;
43
- lastTimestamp = timestamp;
44
- elapsedWhilePaused = 0;
125
+ cleanupAbortListener();
126
+ };
127
+
128
+ const cancel = () => {
129
+ if (finished) return;
130
+ finish();
131
+ };
132
+
133
+ const attachAbortListener = () => {
134
+ cleanupAbortListener();
135
+
136
+ // Preserve semantics: if already aborted, become terminal (and do not attach).
137
+ if (signal?.aborted) {
138
+ finished = true;
139
+ remainingToNext = 0;
140
+ return;
45
141
  }
46
142
 
47
- handle = requestAnimationFrame(tick);
143
+ cleanupAbort = attachAbort(signal, cancel);
48
144
  };
49
145
 
50
- const pause = () => {
51
- if (running && !paused) {
52
- paused = true;
53
- elapsedWhilePaused += performance.now() - lastTimestamp;
54
- cancelAnimationFrame(handle);
146
+ attachAbortListener();
147
+
148
+ const canRunMore = () => count < max;
149
+
150
+ const fire = () => {
151
+ fn?.(count++);
152
+ if (!canRunMore()) {
153
+ finish();
154
+ return false;
55
155
  }
156
+ return true;
56
157
  };
57
158
 
58
- const resume = () => {
59
- if (running && paused) {
60
- paused = false;
61
- lastTimestamp = performance.now();
62
- handle = requestAnimationFrame(tick);
159
+ const tick = (ts) => {
160
+ if (!running || finished) return;
161
+
162
+ if (signal?.aborted) {
163
+ finish();
164
+ return;
165
+ }
166
+
167
+ if (!canRunMore()) {
168
+ finish();
169
+ return;
170
+ }
171
+
172
+ if (lastTs == null) lastTs = ts;
173
+
174
+ const delta = ts - lastTs;
175
+ lastTs = ts;
176
+
177
+ // Decrement remaining time based on frame delta
178
+ remainingToNext -= delta;
179
+
180
+ // Catch-up loop: if we missed multiple intervals, fire multiple times.
181
+ // Protect against infinite loops: intervalMs could be 0.
182
+ const step = Math.max(0, intervalMs);
183
+
184
+ if (step === 0) {
185
+ // If interval is 0ms, treat as "once per frame"
186
+ remainingToNext = 0;
187
+ fire();
188
+ rafId = requestAnimationFrame(tick);
189
+ return;
190
+ }
191
+
192
+ while (remainingToNext <= 0 && !finished) {
193
+ const ok = fire();
194
+ if (!ok) return;
195
+
196
+ // carry over overshoot
197
+ remainingToNext += step;
63
198
  }
199
+
200
+ rafId = requestAnimationFrame(tick);
64
201
  };
65
202
 
66
- const cancel = () => {
67
- if (handle !== null) {
68
- cancelAnimationFrame(handle);
69
- handle = null;
203
+ const startLoop = () => {
204
+ if (finished) return;
205
+
206
+ if (signal?.aborted) {
207
+ finish();
208
+ return;
70
209
  }
71
- running = false;
210
+
211
+ if (!canRunMore()) {
212
+ finish();
213
+ return;
214
+ }
215
+
216
+ running = true;
72
217
  paused = false;
73
- startTimestamp = null;
74
- lastTimestamp = null;
75
- elapsedWhilePaused = 0;
218
+ lastTs = null;
219
+ rafId = requestAnimationFrame(tick);
76
220
  };
77
221
 
78
- const reset = (restart = false) => {
79
- cancel();
80
- count = 0;
81
- if (restart) start();
222
+ const pause = () => {
223
+ if (!running || finished) return;
224
+
225
+ cancelFrame();
226
+
227
+ // Freeze remainingToNext based on time since lastTs
228
+ const currentTime = now(); // ✅ fixed: no shadowing / TDZ
229
+ if (lastTs != null) {
230
+ const delta = currentTime - lastTs;
231
+ remainingToNext = Math.max(0, remainingToNext - delta);
232
+ }
233
+
234
+ lastTs = null;
235
+ running = false;
236
+ paused = true;
82
237
  };
83
238
 
84
- const start = () => {
85
- if (runImmediately) {
86
- fn?.();
87
- count++;
239
+ const resume = () => {
240
+ if (finished || running || !paused) return;
241
+ if (signal?.aborted) return;
242
+
243
+ if (!canRunMore()) {
244
+ finish();
245
+ return;
88
246
  }
89
- running = true;
247
+
248
+ startLoop();
249
+ };
250
+
251
+ const reset = (restart = false) => {
252
+ cancelFrame();
253
+
254
+ count = 0;
255
+ remainingToNext = intervalMs;
256
+ lastTs = null;
257
+
258
+ running = false;
90
259
  paused = false;
91
- lastTimestamp = performance.now();
92
- handle = requestAnimationFrame(tick);
260
+ finished = false;
261
+
262
+ // Re-attach abort on reset (consistent with non-RAF timers)
263
+ attachAbortListener();
264
+ if (finished) return;
265
+
266
+ // If max is already satisfied by definition (<=0 but not Infinity), finish.
267
+ if (!(max > 0) && max !== Infinity) {
268
+ finish();
269
+ return;
270
+ }
271
+
272
+ if (restart) {
273
+ // Optionally honor runImmediately on restart (matching constructor semantics)
274
+ if (runImmediately && canRunMore()) {
275
+ fire();
276
+ if (finished) return;
277
+ }
278
+ startLoop();
279
+ }
93
280
  };
94
281
 
95
282
  // Initial launch
96
- start();
283
+ if (!finished) {
284
+ if (!(max > 0) && max !== Infinity) {
285
+ finish();
286
+ } else {
287
+ if (runImmediately && canRunMore()) {
288
+ fire();
289
+ }
290
+ if (!finished) {
291
+ remainingToNext = Math.max(0, intervalMs);
292
+ startLoop();
293
+ }
294
+ }
295
+ } else {
296
+ cleanupAbortListener();
297
+ }
97
298
 
98
299
  return {
99
300
  pause,
100
301
  resume,
101
302
  cancel,
102
303
  reset,
103
- get isRunning() { return running && !paused; },
104
- get count() { return count; }
304
+ get isRunning() {
305
+ return running;
306
+ },
307
+ get isPaused() {
308
+ return paused;
309
+ },
310
+ get isFinished() {
311
+ return finished;
312
+ },
313
+ get count() {
314
+ return count;
315
+ },
105
316
  };
106
- }
317
+ }
package/src/raf/index.js CHANGED
@@ -1,8 +1,28 @@
1
-
2
1
  // ./raf/index.js
3
2
 
4
- export { afterRaf } from './afterRaf.js';
5
- export { everyRaf } from './everyRaf.js';
6
- export { debounceRaf } from './debounceRaf.js';
7
- export { throttleRaf } from './throttleRaf.js';
8
- export { waitForRaf } from './waitForRaf.js';
3
+ import { afterRaf as _afterRaf } from './afterRaf.js';
4
+ import { everyRaf as _everyRaf } from './everyRaf.js';
5
+ import { debounceRaf as _debounceRaf } from './debounceRaf.js';
6
+ import { throttleRaf as _throttleRaf } from './throttleRaf.js';
7
+ import { waitForRaf as _waitForRaf } from './waitForRaf.js';
8
+
9
+ export function assertRafAvailable() {
10
+ if (typeof requestAnimationFrame !== 'function') {
11
+ throw new Error(
12
+ 'requestAnimationFrame is not available in this environment. ' +
13
+ 'Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.'
14
+ );
15
+ }
16
+ }
17
+
18
+ const guard = (fn) =>
19
+ (...args) => {
20
+ assertRafAvailable();
21
+ return fn(...args);
22
+ };
23
+
24
+ export const afterRaf = guard(_afterRaf);
25
+ export const everyRaf = guard(_everyRaf);
26
+ export const debounceRaf = guard(_debounceRaf);
27
+ export const throttleRaf = guard(_throttleRaf);
28
+ export const waitForRaf = guard(_waitForRaf);