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
@@ -1,106 +1,317 @@
1
-
2
- // ./raf/everyRaf.js
3
-
4
- import { parseDuration } from '../parseDuration.js';
5
-
6
- /**
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
15
- */
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;
21
- let running = false;
22
- let paused = false;
23
- let elapsedWhilePaused = 0;
24
- let count = 0;
25
-
26
- const tick = (timestamp) => {
27
- if (!running || paused) return;
28
-
29
- if (startTimestamp == null) {
30
- startTimestamp = timestamp;
31
- lastTimestamp = timestamp;
32
- }
33
-
34
- const elapsed = timestamp - lastTimestamp + elapsedWhilePaused;
35
-
36
- if (elapsed >= ms) {
37
- if (count >= maxTimes) {
38
- cancel();
39
- return;
40
- }
41
- fn?.();
42
- count++;
43
- lastTimestamp = timestamp;
44
- elapsedWhilePaused = 0;
45
- }
46
-
47
- handle = requestAnimationFrame(tick);
48
- };
49
-
50
- const pause = () => {
51
- if (running && !paused) {
52
- paused = true;
53
- elapsedWhilePaused += performance.now() - lastTimestamp;
54
- cancelAnimationFrame(handle);
55
- }
56
- };
57
-
58
- const resume = () => {
59
- if (running && paused) {
60
- paused = false;
61
- lastTimestamp = performance.now();
62
- handle = requestAnimationFrame(tick);
63
- }
64
- };
65
-
66
- const cancel = () => {
67
- if (handle !== null) {
68
- cancelAnimationFrame(handle);
69
- handle = null;
70
- }
71
- running = false;
72
- paused = false;
73
- startTimestamp = null;
74
- lastTimestamp = null;
75
- elapsedWhilePaused = 0;
76
- };
77
-
78
- const reset = (restart = false) => {
79
- cancel();
80
- count = 0;
81
- if (restart) start();
82
- };
83
-
84
- const start = () => {
85
- if (runImmediately) {
86
- fn?.();
87
- count++;
88
- }
89
- running = true;
90
- paused = false;
91
- lastTimestamp = performance.now();
92
- handle = requestAnimationFrame(tick);
93
- };
94
-
95
- // Initial launch
96
- start();
97
-
98
- return {
99
- pause,
100
- resume,
101
- cancel,
102
- reset,
103
- get isRunning() { return running && !paused; },
104
- get count() { return count; }
105
- };
106
- }
1
+ // ./raf/everyRaf.js
2
+ import { resolveDelayFnOptions } from '../resolveDelayAndFn.js';
3
+ import { attachAbort } from '../abort.js';
4
+ import { now } from '../now.js';
5
+
6
+ const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
7
+
8
+ /**
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
+ * }}
38
+ */
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
+
100
+ let running = false;
101
+ let paused = false;
102
+ let finished = false;
103
+
104
+ const cancelFrame = () => {
105
+ if (rafId) cancelAnimationFrame(rafId);
106
+ rafId = 0;
107
+ };
108
+
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;
121
+
122
+ lastTs = null;
123
+ remainingToNext = 0;
124
+
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;
141
+ }
142
+
143
+ cleanupAbort = attachAbort(signal, cancel);
144
+ };
145
+
146
+ attachAbortListener();
147
+
148
+ const canRunMore = () => count < max;
149
+
150
+ const fire = () => {
151
+ fn?.(count++);
152
+ if (!canRunMore()) {
153
+ finish();
154
+ return false;
155
+ }
156
+ return true;
157
+ };
158
+
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;
198
+ }
199
+
200
+ rafId = requestAnimationFrame(tick);
201
+ };
202
+
203
+ const startLoop = () => {
204
+ if (finished) return;
205
+
206
+ if (signal?.aborted) {
207
+ finish();
208
+ return;
209
+ }
210
+
211
+ if (!canRunMore()) {
212
+ finish();
213
+ return;
214
+ }
215
+
216
+ running = true;
217
+ paused = false;
218
+ lastTs = null;
219
+ rafId = requestAnimationFrame(tick);
220
+ };
221
+
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;
237
+ };
238
+
239
+ const resume = () => {
240
+ if (finished || running || !paused) return;
241
+ if (signal?.aborted) return;
242
+
243
+ if (!canRunMore()) {
244
+ finish();
245
+ return;
246
+ }
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;
259
+ paused = false;
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
+ }
280
+ };
281
+
282
+ // Initial launch
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
+ }
298
+
299
+ return {
300
+ pause,
301
+ resume,
302
+ cancel,
303
+ reset,
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
+ },
316
+ };
317
+ }
package/src/raf/index.js CHANGED
@@ -1,8 +1,28 @@
1
-
2
- // ./raf/index.js
3
-
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';
1
+ // ./raf/index.js
2
+
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);
@@ -1,38 +1,182 @@
1
-
2
- // ./raf/throttleRaf.js
3
-
4
- /**
5
- * Throttles a function using requestAnimationFrame with optional frame skipping.
6
- * Ensures the function runs at most once per N-frames.
7
- * - frameSkip = 0 → run every frame
8
- * - frameSkip = 1 → run every 2nd frame
9
- * - frameSkip = 2 → run every 3rd frame, etc.
10
- *
11
- * @param {Function} fn - Function to throttle
12
- * @param {number} [frameSkip=0] - Number of frames to skip between calls
13
- * @returns {Function} throttled function
14
- */
15
- export function throttleRaf(fn, frameSkip = 0) {
16
- let scheduled = false;
17
- let lastArgs = null;
18
- let frameCount = 0;
19
-
20
- return (...args) => {
21
- lastArgs = args;
22
-
23
- if (!scheduled) {
24
- scheduled = true;
25
- requestAnimationFrame(function tick() {
26
- if (frameCount >= frameSkip) {
27
- fn(...lastArgs);
28
- frameCount = 0;
29
- scheduled = false;
30
- } else {
31
- frameCount++;
32
- requestAnimationFrame(tick);
33
- }
34
- });
35
- }
36
- };
37
- }
38
-
1
+ // ./raf/throttleRaf.js
2
+ import { pendingAbort } from '../abort.js';
3
+
4
+ const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
5
+
6
+ /**
7
+ * Throttles a function using `requestAnimationFrame`, with optional frame skipping.
8
+ *
9
+ * Preferred:
10
+ * - throttleRaf(fn, [frameSkip], [options])
11
+ *
12
+ * Also supported:
13
+ * - throttleRaf(fn, [options]) // frameSkip defaults to 0
14
+ *
15
+ * Executes at most once every `(frameSkip + 1)` frames.
16
+ *
17
+ * Argument behavior while throttled:
18
+ * - trailing=true (default): uses the latest args/this seen while waiting
19
+ * - trailing=false: keeps the first args/this and ignores later calls until it fires
20
+ *
21
+ * AbortSignal:
22
+ * - If `signal` is provided, abort will cancel any pending scheduled execution.
23
+ * - Listener is attached only while a call is pending.
24
+ *
25
+ * @template {(...args: any[]) => any} T
26
+ * @param {T} fn
27
+ * @param {number|{signal?: AbortSignal, trailing?: boolean}} [frameSkipOrOptions=0]
28
+ * @param {{signal?: AbortSignal, trailing?: boolean}} [maybeOptions]
29
+ * @returns {T & { cancel: () => void, flush: () => void }}
30
+ */
31
+ export function throttleRaf(fn, frameSkipOrOptions = 0, maybeOptions) {
32
+ if (typeof fn !== 'function') {
33
+ throw new TypeError(`Expected a function, got: ${typeof fn}`);
34
+ }
35
+
36
+ const frameSkip = typeof frameSkipOrOptions === 'number' ? frameSkipOrOptions : 0;
37
+
38
+ const options = isPlainOptions(frameSkipOrOptions)
39
+ ? frameSkipOrOptions
40
+ : isPlainOptions(maybeOptions)
41
+ ? maybeOptions
42
+ : {};
43
+
44
+ const signal = options.signal;
45
+ const trailing = options.trailing ?? true;
46
+
47
+ // Normalize once: int >= 0
48
+ const skip = Math.max(0, frameSkip | 0);
49
+
50
+ let scheduled = false;
51
+ let rafId = 0;
52
+
53
+ /** @type {any[] | null} */
54
+ let lastArgs = null;
55
+ /** @type {any | null} */
56
+ let lastThis = null;
57
+
58
+ // countdown for skip-path only
59
+ let remaining = skip;
60
+
61
+ const abort = pendingAbort(signal, () => cancel());
62
+
63
+ const clearState = () => {
64
+ scheduled = false;
65
+
66
+ if (rafId) cancelAnimationFrame(rafId);
67
+ rafId = 0;
68
+
69
+ remaining = skip;
70
+
71
+ lastArgs = null;
72
+ lastThis = null;
73
+
74
+ abort.remove();
75
+ };
76
+
77
+ const cancel = () => {
78
+ clearState();
79
+ };
80
+
81
+ const invoke = () => {
82
+ if (!lastArgs) return;
83
+
84
+ const args = lastArgs;
85
+ const ctx = lastThis;
86
+
87
+ // Clear first to aid GC + prevent re-entrancy oddities
88
+ lastArgs = null;
89
+ lastThis = null;
90
+
91
+ abort.remove();
92
+ fn.apply(ctx, args);
93
+ };
94
+
95
+ const fire = () => {
96
+ scheduled = false;
97
+ rafId = 0;
98
+ remaining = skip;
99
+ invoke();
100
+ };
101
+
102
+ const tickSkip = () => {
103
+ if (!scheduled) return;
104
+
105
+ if (signal?.aborted) {
106
+ cancel();
107
+ return;
108
+ }
109
+
110
+ if (remaining === 0) {
111
+ fire();
112
+ return;
113
+ }
114
+
115
+ remaining -= 1;
116
+ rafId = requestAnimationFrame(tickSkip);
117
+ };
118
+
119
+ // Fast path for skip === 0
120
+ const tick0 = () => {
121
+ if (!scheduled) return;
122
+
123
+ if (signal?.aborted) {
124
+ cancel();
125
+ return;
126
+ }
127
+
128
+ fire();
129
+ };
130
+
131
+ const schedule =
132
+ skip === 0
133
+ ? () => {
134
+ scheduled = true;
135
+ abort.add();
136
+ rafId = requestAnimationFrame(tick0);
137
+ }
138
+ : () => {
139
+ scheduled = true;
140
+ remaining = skip;
141
+ abort.add();
142
+ rafId = requestAnimationFrame(tickSkip);
143
+ };
144
+
145
+ /** @type {any} */
146
+ const throttled = function (...args) {
147
+ if (signal?.aborted) return;
148
+
149
+ // While waiting, keep latest args only if trailing=true
150
+ if (!scheduled || trailing) {
151
+ lastArgs = args;
152
+ lastThis = this;
153
+ }
154
+
155
+ if (scheduled) return;
156
+ schedule();
157
+ };
158
+
159
+ throttled.cancel = cancel;
160
+
161
+ throttled.flush = () => {
162
+ if (!scheduled) return;
163
+
164
+ if (signal?.aborted) {
165
+ cancel();
166
+ return;
167
+ }
168
+
169
+ // Cancel RAF and invoke immediately
170
+ scheduled = false;
171
+ if (rafId) cancelAnimationFrame(rafId);
172
+ rafId = 0;
173
+ remaining = skip;
174
+
175
+ invoke();
176
+ };
177
+
178
+ // If already aborted at creation time, ensure clean slate.
179
+ if (signal?.aborted) cancel();
180
+
181
+ return throttled;
182
+ }