timeout-flow 0.0.18 → 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.
@@ -1,317 +1,317 @@
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
- };
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
317
  }