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.
- package/README.md +239 -144
- package/dist/timeout-flow.min.js +1 -6
- package/package.json +2 -1
- package/src/AfterTimer.js +64 -3
- package/src/EveryTimer.js +139 -18
- package/src/TimeoutFlow.js +291 -118
- package/src/TimerBase.js +81 -23
- package/src/abort.js +75 -0
- package/src/after.js +20 -71
- package/src/context-js.bat +58 -0
- package/src/context.txt +2604 -0
- package/src/debounce.js +90 -24
- package/src/every.js +19 -105
- package/src/index.js +7 -2
- package/src/now.js +23 -0
- package/src/parseDuration.js +22 -20
- package/src/raf/afterRaf.js +198 -66
- package/src/raf/debounceRaf.js +108 -26
- package/src/raf/everyRaf.js +278 -67
- package/src/raf/index.js +26 -6
- package/src/raf/throttleRaf.js +175 -31
- package/src/raf/waitForRaf.js +82 -14
- package/src/resolveDelayAndFn.js +69 -7
- package/src/retry.js +152 -12
- package/src/throttle.js +120 -26
- package/src/waitFor.js +68 -24
- package/types/AfterTimer.d.ts +8 -2
- package/types/EveryTimer.d.ts +21 -4
- package/types/TimeoutFlow.d.ts +6 -18
- package/types/TimerBase.d.ts +15 -4
- package/types/abort.d.ts +31 -0
- package/types/after.d.ts +22 -22
- package/types/debounce.d.ts +28 -6
- package/types/every.d.ts +20 -28
- package/types/index.d.ts +1 -1
- package/types/now.d.ts +1 -0
- package/types/raf/afterRaf.d.ts +35 -5
- package/types/raf/debounceRaf.d.ts +27 -6
- package/types/raf/everyRaf.d.ts +39 -9
- package/types/raf/index.d.ts +6 -5
- package/types/raf/throttleRaf.d.ts +33 -10
- package/types/raf/waitForRaf.d.ts +10 -4
- package/types/resolveDelayAndFn.d.ts +27 -0
- package/types/retry.d.ts +25 -8
- package/types/throttle.d.ts +28 -6
- package/types/waitFor.d.ts +11 -6
package/README.md
CHANGED
|
@@ -1,54 +1,68 @@
|
|
|
1
1
|
# TimeoutFlow
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/timeout-flow)
|
|
4
|
-
[](https://bundlephobia.com/package
|
|
4
|
+
[](https://bundlephobia.com/package/timeout-flow)
|
|
5
5
|
[](https://www.npmjs.com/package/timeout-flow)
|
|
6
6
|
[](https://github.com/iWhatty/TimeoutFlow-js)
|
|
7
7
|
|
|
8
8
|
**Fluent, human-readable time control for JavaScript.**
|
|
9
9
|
|
|
10
|
-
TimeoutFlow makes working with time-based logic intuitive — think of it as a modern, composable upgrade to `setTimeout` and `setInterval`, with
|
|
10
|
+
TimeoutFlow makes working with time-based logic intuitive — think of it as a modern, composable upgrade to `setTimeout` and `setInterval`, with chaining, conditional logic, pause/resume control, retries, RAF utilities, and more.
|
|
11
11
|
|
|
12
|
-
* Minified: 6
|
|
13
|
-
* Gzipped: 2
|
|
12
|
+
* Minified: ~6–7 KB
|
|
13
|
+
* Gzipped: ~2–3 KB
|
|
14
|
+
* Zero dependencies
|
|
15
|
+
* ESM-first, tree-shakeable
|
|
14
16
|
|
|
15
17
|
---
|
|
16
18
|
|
|
17
|
-
|
|
19
|
+
# Philosophy
|
|
18
20
|
|
|
19
|
-
|
|
20
|
-
It
|
|
21
|
+
TimeoutFlow is not just a wrapper around timers.
|
|
22
|
+
It’s a composable toolkit for expressing time as readable logic.
|
|
21
23
|
|
|
22
|
-
|
|
24
|
+
Temporal behavior should be:
|
|
23
25
|
|
|
24
|
-
* **Readable**
|
|
25
|
-
* **Composable**
|
|
26
|
-
* **Controllable**
|
|
27
|
-
* **Branchable**
|
|
28
|
-
* **Tiny**
|
|
26
|
+
* **Readable** — durations like `"1s"` and `"500ms"` beat magic numbers.
|
|
27
|
+
* **Composable** — sequencing should be declarative.
|
|
28
|
+
* **Controllable** — timers should pause, resume, cancel.
|
|
29
|
+
* **Branchable** — real flows need `if`, `while`, `label`, `jumpTo()`.
|
|
30
|
+
* **Tiny** — no runtime bloat.
|
|
29
31
|
|
|
30
|
-
|
|
31
|
-
and a fluent builder (`flow()`) to script rich behavior over time — like a timeline you can control.
|
|
32
|
+
> Think of TimeoutFlow as `setTimeout()` with superpowers.
|
|
32
33
|
|
|
33
|
-
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
# Clean Signatures
|
|
34
37
|
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
TimeoutFlow supports **both** natural-language ordering and function-first ordering.
|
|
39
|
+
|
|
40
|
+
You can write:
|
|
37
41
|
|
|
38
42
|
```js
|
|
39
|
-
|
|
40
|
-
.after('1s', () => console.log('Start'))
|
|
41
|
-
.every('500ms', (i) => console.log(`Tick ${i}`), 3)
|
|
42
|
-
.after('1s', () => console.log('Done'))
|
|
43
|
-
.start();
|
|
43
|
+
after('1s', done);
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
|
|
47
|
-
|
|
46
|
+
Or:
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
after(done, '1s');
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Both are valid.
|
|
53
|
+
|
|
54
|
+
This applies to:
|
|
55
|
+
|
|
56
|
+
* `after()`
|
|
57
|
+
* `every()`
|
|
58
|
+
* `debounce()`
|
|
59
|
+
* `throttle()`
|
|
60
|
+
|
|
61
|
+
Use whichever reads best in your codebase.
|
|
48
62
|
|
|
49
63
|
---
|
|
50
64
|
|
|
51
|
-
|
|
65
|
+
# Installation
|
|
52
66
|
|
|
53
67
|
```bash
|
|
54
68
|
npm install timeout-flow
|
|
@@ -56,182 +70,263 @@ npm install timeout-flow
|
|
|
56
70
|
|
|
57
71
|
---
|
|
58
72
|
|
|
59
|
-
|
|
73
|
+
# Unified Control Surface
|
|
60
74
|
|
|
61
|
-
|
|
62
|
-
* `every("500ms", fn, count?)` — repeat execution with optional limit (via `EveryTimer`)
|
|
63
|
-
* `flow()` — create fluent, chainable timelines with:
|
|
75
|
+
Most time-based primitives return a **controller object**:
|
|
64
76
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
77
|
+
```js
|
|
78
|
+
import { after } from 'timeout-flow';
|
|
79
|
+
|
|
80
|
+
function done() {
|
|
81
|
+
console.log('done');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const ctrl = after('1s', done);
|
|
85
|
+
|
|
86
|
+
ctrl.pause();
|
|
87
|
+
ctrl.resume();
|
|
88
|
+
ctrl.cancel();
|
|
89
|
+
ctrl.reset?.();
|
|
90
|
+
|
|
91
|
+
console.log(ctrl.isRunning);
|
|
92
|
+
console.log(ctrl.isPaused);
|
|
93
|
+
console.log(ctrl.isFinished);
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Shared by:
|
|
97
|
+
|
|
98
|
+
* `after()`
|
|
99
|
+
* `every()`
|
|
100
|
+
* `afterRaf()`
|
|
101
|
+
* `everyRaf()`
|
|
102
|
+
|
|
103
|
+
All controllers are:
|
|
104
|
+
|
|
105
|
+
* Pause-safe (paused time does not count)
|
|
106
|
+
* Cancel-safe
|
|
107
|
+
* Monotonic-time based
|
|
108
|
+
* AbortSignal-aware (where supported)
|
|
69
109
|
|
|
70
110
|
---
|
|
71
111
|
|
|
72
|
-
|
|
112
|
+
# Core Primitives
|
|
113
|
+
|
|
114
|
+
## after()
|
|
115
|
+
|
|
116
|
+
Run once after a delay.
|
|
73
117
|
|
|
74
118
|
```js
|
|
75
|
-
// 1. Delayed Execution
|
|
76
119
|
import { after } from 'timeout-flow';
|
|
77
|
-
after('2s', () => console.log('Waited 2 seconds...'));
|
|
78
120
|
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
wait('2.5s', () => ticker.pause());
|
|
83
|
-
wait('4s', () => ticker.resume());
|
|
121
|
+
function greet() {
|
|
122
|
+
console.log('Hello');
|
|
123
|
+
}
|
|
84
124
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const search = debounce('300ms', (e) => {
|
|
88
|
-
console.log('Searching for:', e.target.value);
|
|
89
|
-
});
|
|
90
|
-
document.querySelector('input').addEventListener('input', search);
|
|
125
|
+
after('2s', greet);
|
|
126
|
+
```
|
|
91
127
|
|
|
92
|
-
|
|
93
|
-
import { retry } from 'timeout-flow';
|
|
94
|
-
await retry(() => fetch('/api/data'), {
|
|
95
|
-
attempts: 4,
|
|
96
|
-
delay: '1s',
|
|
97
|
-
backoff: true
|
|
98
|
-
});
|
|
128
|
+
---
|
|
99
129
|
|
|
100
|
-
|
|
101
|
-
import { waitFor } from 'timeout-flow';
|
|
102
|
-
await waitFor(() => document.querySelector('#loaded'), {
|
|
103
|
-
interval: '250ms',
|
|
104
|
-
timeout: '5s'
|
|
105
|
-
});
|
|
106
|
-
console.log('Element loaded!');
|
|
130
|
+
## every()
|
|
107
131
|
|
|
108
|
-
|
|
109
|
-
import { flow } from 'timeout-flow';
|
|
110
|
-
flow()
|
|
111
|
-
.after('1s', () => console.log('Step 1'))
|
|
112
|
-
.every('500ms', (i) => console.log(`Tick ${i}`), 3)
|
|
113
|
-
.after('1s', () => console.log('Final Step'))
|
|
114
|
-
.start();
|
|
132
|
+
Repeat execution with optional limit.
|
|
115
133
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
flow()
|
|
119
|
-
.after('1s', () => console.log('Boot sequence'))
|
|
120
|
-
.if(() => debug)
|
|
121
|
-
.after('500ms', () => console.log('Debug logs enabled'))
|
|
122
|
-
.label('loop')
|
|
123
|
-
.every('1s', i => console.log(`Frame ${i}`), 3)
|
|
124
|
-
.after('500ms', () => console.log('Restarting...'))
|
|
125
|
-
.jumpTo('loop')
|
|
126
|
-
.start();
|
|
134
|
+
```js
|
|
135
|
+
import { every } from 'timeout-flow';
|
|
127
136
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
.after('1s', () => console.log('Energy depleted'))
|
|
134
|
-
.start();
|
|
137
|
+
function tick(i) {
|
|
138
|
+
console.log('Tick', i);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const ticker = every('1s', tick, { max: 5 });
|
|
135
142
|
```
|
|
136
143
|
|
|
137
144
|
---
|
|
138
145
|
|
|
139
|
-
##
|
|
146
|
+
## debounce()
|
|
147
|
+
|
|
148
|
+
Delay execution until inactivity.
|
|
140
149
|
|
|
141
150
|
```js
|
|
142
|
-
import { debounce
|
|
143
|
-
|
|
151
|
+
import { debounce } from 'timeout-flow';
|
|
152
|
+
|
|
153
|
+
function search(event) {
|
|
154
|
+
console.log('Searching for:', event.target.value);
|
|
155
|
+
}
|
|
144
156
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
157
|
+
const debouncedSearch = debounce('300ms', search);
|
|
158
|
+
|
|
159
|
+
debouncedSearch.cancel();
|
|
160
|
+
debouncedSearch.flush();
|
|
161
|
+
```
|
|
149
162
|
|
|
150
163
|
---
|
|
151
164
|
|
|
152
|
-
##
|
|
165
|
+
## throttle()
|
|
153
166
|
|
|
154
|
-
|
|
167
|
+
Limit execution frequency.
|
|
155
168
|
|
|
156
|
-
|
|
169
|
+
```js
|
|
170
|
+
import { throttle } from 'timeout-flow';
|
|
157
171
|
|
|
158
|
-
|
|
172
|
+
function handleScroll() {
|
|
173
|
+
console.log('scroll');
|
|
174
|
+
}
|
|
159
175
|
|
|
160
|
-
|
|
161
|
-
| -------------------------- | ------------------------------------------------------------------- | -------------------------------------------------- |
|
|
162
|
-
| `afterRaf()` | Runs a function **once after N ms**, using `requestAnimationFrame`. | Idle effects, UI post-load, paint batching |
|
|
163
|
-
| `everyRaf()` | Repeats a function **every N ms**, throttled via frames. | Sanity loops, smooth polling, visual checks |
|
|
164
|
-
| `debounceRaf()` | Debounces a function using **frames instead of timeouts**. | Drag/move handlers, visual updates |
|
|
165
|
-
| `debounceRaf('300ms', fn)` | Debounces like traditional debounce, but frame-aware. | Resize events, paused background flows |
|
|
166
|
-
| `throttleRaf()` | Throttles execution to **at most once per frame**. | Scroll events, pointermove, paint-heavy flows |
|
|
167
|
-
| `throttleRaf(fn, 2)` | Throttles to once every 3 frames (`frameSkip = 2`). | Advanced visuals, slower sync without timers |
|
|
168
|
-
| `waitForRaf()` | Waits for a condition to become true using a frame-based loop. | DOM readiness, layout stability, visibility checks |
|
|
176
|
+
const onScroll = throttle('250ms', handleScroll);
|
|
169
177
|
|
|
170
|
-
|
|
178
|
+
onScroll.cancel();
|
|
179
|
+
onScroll.flush();
|
|
180
|
+
```
|
|
171
181
|
|
|
172
|
-
|
|
173
|
-
* **Background-tab safe**: No CPU use when inactive
|
|
174
|
-
* **Energy efficient**: Great for battery-conscious apps
|
|
175
|
-
* **Smoother UX**: Especially under load or heavy visuals
|
|
182
|
+
---
|
|
176
183
|
|
|
177
|
-
|
|
184
|
+
## retry()
|
|
178
185
|
|
|
179
|
-
|
|
180
|
-
import { debounceRaf } from 'timeout-flow';
|
|
186
|
+
Retry async operations with backoff + jitter.
|
|
181
187
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
});
|
|
188
|
+
```js
|
|
189
|
+
import { retry } from 'timeout-flow';
|
|
185
190
|
|
|
186
|
-
|
|
187
|
-
|
|
191
|
+
async function fetchData() {
|
|
192
|
+
return fetch('/api/data');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
await retry(fetchData, {
|
|
196
|
+
attempts: 5,
|
|
197
|
+
delay: '500ms',
|
|
198
|
+
backoff: true,
|
|
199
|
+
factor: 2,
|
|
200
|
+
maxDelay: '5s',
|
|
201
|
+
jitter: 'decorrelated'
|
|
188
202
|
});
|
|
189
203
|
```
|
|
190
204
|
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
## waitFor()
|
|
208
|
+
|
|
209
|
+
Wait until a condition becomes true.
|
|
210
|
+
|
|
191
211
|
```js
|
|
192
|
-
import {
|
|
212
|
+
import { waitFor } from 'timeout-flow';
|
|
193
213
|
|
|
194
|
-
|
|
195
|
-
|
|
214
|
+
await waitFor(function checkLoaded() {
|
|
215
|
+
return document.querySelector('#loaded');
|
|
216
|
+
}, {
|
|
217
|
+
interval: '250ms',
|
|
218
|
+
timeout: '5s',
|
|
219
|
+
immediate: true
|
|
196
220
|
});
|
|
197
221
|
```
|
|
198
222
|
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
# Fluent Timeline
|
|
226
|
+
|
|
227
|
+
Build declarative time flows.
|
|
228
|
+
|
|
199
229
|
```js
|
|
200
|
-
import {
|
|
230
|
+
import { flow } from 'timeout-flow';
|
|
201
231
|
|
|
202
|
-
|
|
203
|
-
console.log('
|
|
204
|
-
}
|
|
232
|
+
function stepOne() {
|
|
233
|
+
console.log('Step 1');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function tick(i) {
|
|
237
|
+
console.log('Tick', i);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function finalStep() {
|
|
241
|
+
console.log('Final Step');
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
flow()
|
|
245
|
+
.after('1s', stepOne)
|
|
246
|
+
.every('500ms', tick, { max: 3 })
|
|
247
|
+
.after('1s', finalStep)
|
|
248
|
+
.start();
|
|
205
249
|
```
|
|
206
250
|
|
|
251
|
+
Flow reads like a timeline and keeps duration-first ordering for readability.
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
# AbortSignal Support
|
|
256
|
+
|
|
257
|
+
Many utilities accept `{ signal }` for automatic cancellation.
|
|
258
|
+
|
|
207
259
|
```js
|
|
208
|
-
import {
|
|
260
|
+
import { after } from 'timeout-flow';
|
|
209
261
|
|
|
210
|
-
const
|
|
211
|
-
handleScroll(e);
|
|
212
|
-
});
|
|
262
|
+
const ac = new AbortController();
|
|
213
263
|
|
|
214
|
-
|
|
264
|
+
function doWork() {
|
|
265
|
+
console.log('Will not run if aborted');
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
after('2s', doWork, { signal: ac.signal });
|
|
269
|
+
|
|
270
|
+
ac.abort();
|
|
215
271
|
```
|
|
216
272
|
|
|
273
|
+
If already aborted at creation time, no work is scheduled.
|
|
274
|
+
|
|
275
|
+
---
|
|
276
|
+
|
|
277
|
+
# RAF Utilities
|
|
278
|
+
|
|
279
|
+
Frame-based timing powered by `requestAnimationFrame`.
|
|
280
|
+
|
|
281
|
+
Ideal for visual updates, scroll handlers, layout checks, and animation loops.
|
|
282
|
+
|
|
283
|
+
## Available
|
|
284
|
+
|
|
285
|
+
* `afterRaf()`
|
|
286
|
+
* `everyRaf()`
|
|
287
|
+
* `debounceRaf()`
|
|
288
|
+
* `throttleRaf()`
|
|
289
|
+
* `waitForRaf()`
|
|
290
|
+
|
|
291
|
+
## Example
|
|
292
|
+
|
|
217
293
|
```js
|
|
218
|
-
import {
|
|
294
|
+
import { throttleRaf } from 'timeout-flow';
|
|
219
295
|
|
|
220
|
-
|
|
296
|
+
function drawFrame() {
|
|
297
|
+
console.log('draw');
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const onScroll = throttleRaf(drawFrame);
|
|
301
|
+
|
|
302
|
+
onScroll.cancel();
|
|
303
|
+
onScroll.flush();
|
|
221
304
|
```
|
|
222
305
|
|
|
223
|
-
|
|
306
|
+
---
|
|
307
|
+
|
|
308
|
+
# Public API
|
|
224
309
|
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
310
|
+
```js
|
|
311
|
+
import {
|
|
312
|
+
after,
|
|
313
|
+
every,
|
|
314
|
+
debounce,
|
|
315
|
+
throttle,
|
|
316
|
+
retry,
|
|
317
|
+
waitFor,
|
|
318
|
+
flow,
|
|
319
|
+
|
|
320
|
+
afterRaf,
|
|
321
|
+
everyRaf,
|
|
322
|
+
debounceRaf,
|
|
323
|
+
throttleRaf,
|
|
324
|
+
waitForRaf
|
|
325
|
+
} from 'timeout-flow';
|
|
326
|
+
```
|
|
232
327
|
|
|
233
328
|
---
|
|
234
329
|
|
|
235
|
-
|
|
330
|
+
# License
|
|
236
331
|
|
|
237
|
-
|
|
332
|
+
--{DR.WATT v3.0}--
|
package/dist/timeout-flow.min.js
CHANGED
|
@@ -1,7 +1,2 @@
|
|
|
1
1
|
// TimeoutFlow - Fluent timer + RAF control library
|
|
2
|
-
var O=e=>{throw TypeError(e)};var G=(e,t,n)=>t.has(e)||O("Cannot "+n);var u=(e,t,n)=>(G(e,t,"read from private field"),n?n.call(e):t.get(e)),d=(e,t,n)=>t.has(e)?O("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),m=(e,t,n,l)=>(G(e,t,"write to private field"),l?l.call(e,n):t.set(e,n),n),S=(e,t,n)=>(G(e,t,"access private method"),n);var Q=(e,t,n,l)=>({set _(o){m(e,t,o,n)},get _(){return u(e,t,l)}});var U=Object.freeze(JSON.parse(`{
|
|
3
|
-
"ms": 1,
|
|
4
|
-
"s": 1000,
|
|
5
|
-
"m": 60000,
|
|
6
|
-
"h": 3600000
|
|
7
|
-
}`));function h(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e!="string")throw new TypeError(`Expected a duration string or number, got ${typeof e}`);e=e.toLowerCase().trim();let t=e.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!t)throw new Error(`Invalid duration format: "${e}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let[,n,l]=t;return parseFloat(n)*U[l]}var k,$,R,I,D,C=class{constructor(t){d(this,k);d(this,$,null);d(this,R);d(this,I,null);d(this,D,!1);m(this,k,h(t)),m(this,R,u(this,k))}get isRunning(){return u(this,D)}pause(){u(this,D)&&(clearTimeout(u(this,I)),m(this,R,u(this,R)-(Date.now()-u(this,$))),m(this,D,!1))}resume(t,n=null){!u(this,D)&&u(this,R)>0&&(m(this,$,Date.now()),m(this,D,!0),m(this,I,setTimeout(()=>{m(this,D,!1),t?.()},n??u(this,R))))}cancel(){clearTimeout(u(this,I)),m(this,D,!1),m(this,I,null)}reset(){this.cancel(),m(this,R,u(this,k))}};k=new WeakMap,$=new WeakMap,R=new WeakMap,I=new WeakMap,D=new WeakMap;var _=class extends C{constructor(t,n,l){super(t),this.resume(()=>{n?.(),l?.()})}};function H(e,t,n){return new _(e,t,n)}var L,N,q,b,T,v,E,M,z,B=class{constructor(t,n,l=1/0,o=!1){d(this,M);d(this,L);d(this,N);d(this,q);d(this,b,0);d(this,T,!1);d(this,v,null);d(this,E,()=>{var t;if(u(this,b)>=u(this,q)){this.cancel();return}(t=u(this,N))==null||t.call(this,Q(this,b)._++),S(this,M,z).call(this)});m(this,L,h(t)),m(this,N,n),m(this,q,l),o?u(this,E).call(this):S(this,M,z).call(this)}get count(){return u(this,b)}get isRunning(){return u(this,T)}pause(){u(this,v)?.pause(),m(this,T,!1)}resume(){!u(this,T)&&u(this,b)<u(this,q)&&(u(this,v)?.resume(u(this,E)),m(this,T,!0))}cancel(){u(this,v)?.cancel(),m(this,T,!1)}reset(t=!1){this.cancel(),m(this,b,0),t&&S(this,M,z).call(this)}};L=new WeakMap,N=new WeakMap,q=new WeakMap,b=new WeakMap,T=new WeakMap,v=new WeakMap,E=new WeakMap,M=new WeakSet,z=function(){m(this,v,new C(u(this,L))),m(this,T,!0),u(this,v).resume(u(this,E))};function K(e,t,n=1/0,l=!1){return new B(e,t,n,l)}function V(){let e=[],t=0,n=!1,l=!1,o=!1,i=1/0,s=0,f=null,a=new Map,c=null,y=[],x=!1,F=null,A=null,w={after(r,p){return e.push({type:"after",duration:r,fn:p}),w},every(r,p,W=1/0){return e.push({type:"every",duration:r,fn:p,times:W,whileCondition:F,doWhileCondition:A}),F=null,A=null,w},loop(r=!0){return o=!0,i=r===!0?1/0:r,w},onFinish(r){return f=r,w},start(){return l=!1,n=!1,t=0,s=0,P(),w},pause(){n||l||(n=!0,e[t]?.controller?.pause?.())},resume(){!n||l||(n=!1,e[t]?.controller?.resume?.())},cancel(){l=!0;let r=e[t];r?.controller?.cancel?.(),r.controller=null},reset(){return w.cancel(),e.length=0,t=0,s=0,f=null,w},get isPaused(){return n},label(r){return a.set(r,e.length),w},jumpTo(r){return c=r,w},if(r){return y.push(()=>typeof r=="function"?r():!!r),w},unless(r){return y.push(()=>!(typeof r=="function"?r():r)),w},while(r){return F=()=>typeof r=="function"?r():!!r,w},doWhile(r){return A=()=>typeof r=="function"?r():!!r,w}};function g(r=null){r?.controller&&(r.controller=null),t++,P()}function P(){if(l||n)return;if(c){let p=a.get(c);if(typeof p=="number")t=p;else throw new Error(`Label "${c}" not found`);c=null}if(y.length>0&&(y.shift()()||(x=!0)),x){let p=e[t];if(!p||p.type==="label")x=!1;else return g(r)}let r=e[t];if(!r||t>=e.length){o&&++s<i?(t=0,P()):f?.();return}if(r.type==="after"){r.controller=H(r.duration,r.fn,()=>g(r));return}if(r.type==="every"){let p=0,W=!0,j=K(r.duration,()=>{if(!(n||l)&&(r.whileCondition&&!r.whileCondition()||(r.fn(p++),W=!1,!W&&r.doWhileCondition&&!r.doWhileCondition())||p>=r.times))return j.cancel(),g(r)},r.times);r.controller=j}if(r.type==="label")return g(r)}return w}function J(e,t){let n,l;if(typeof e=="function"?(n=e,l=t):(n=t,l=e),typeof n!="function")throw new TypeError(`Expected a function as one argument, got: ${typeof n}`);let o=h(l);return{fn:n,delay:o}}function X(e,t,n=!0){let{fn:l,delay:o}=J(e,t),i=0,s=null,f=function(...a){let c=this,y=Date.now(),x=y-i;x>=o?(i=y,l.apply(c,a)):n&&!s&&(s=setTimeout(()=>{i=Date.now(),s=null,l.apply(c,a)},o-x))};return f.cancel=()=>{clearTimeout(s),s=null},f}function Y(e,t){let{fn:n,delay:l}=J(e,t),o=null,i=function(...s){clearTimeout(o),o=setTimeout(()=>n.apply(this,s),l)};return i.cancel=()=>{clearTimeout(o),o=null},i}function Z(e,{interval:t="250ms",timeout:n}={}){return new Promise((l,o)=>{let i=Date.now(),s=typeof t=="string"?h(t):t,f=n?h(n):null,c=setInterval(()=>{e()?(clearInterval(c),l()):f&&Date.now()-i>=f&&(clearInterval(c),o(new Error("waitFor timed out")))},s)})}async function ee(e,{attempts:t=3,delay:n="500ms",backoff:l=!1}={}){let o=h(n);for(let i=0;i<t;i++)try{return await e()}catch(s){if(i===t-1)throw s;let f=l?o*Math.pow(2,i):o;await new Promise(a=>setTimeout(a,f))}}function te(e,t,n){let l=typeof e=="string"?h(e):e,o=null,i=null,s=null,f=0,a=!0,c=A=>{if(!a)return;i==null&&(i=A),A-i+f>=l?(a=!1,t?.(),n?.()):o=requestAnimationFrame(c)},y=()=>{a&&o!==null&&(cancelAnimationFrame(o),s=performance.now(),a=!1)},x=()=>{!a&&s!==null&&(f+=performance.now()-s,a=!0,o=requestAnimationFrame(c))},F=()=>{o!==null&&(cancelAnimationFrame(o),o=null),a=!1};return o=requestAnimationFrame(c),{pause:y,resume:x,cancel:F,get isRunning(){return a}}}function ne(e,t,n=1/0,l=!1){let o=typeof e=="string"?h(e):e,i=null,s=null,f=null,a=!1,c=!1,y=0,x=0,F=p=>{if(!a||c)return;if(s==null&&(s=p,f=p),p-f+y>=o){if(x>=n){g();return}t?.(),x++,f=p,y=0}i=requestAnimationFrame(F)},A=()=>{a&&!c&&(c=!0,y+=performance.now()-f,cancelAnimationFrame(i))},w=()=>{a&&c&&(c=!1,f=performance.now(),i=requestAnimationFrame(F))},g=()=>{i!==null&&(cancelAnimationFrame(i),i=null),a=!1,c=!1,s=null,f=null,y=0},P=(p=!1)=>{g(),x=0,p&&r()},r=()=>{l&&(t?.(),x++),a=!0,c=!1,f=performance.now(),i=requestAnimationFrame(F)};return r(),{pause:A,resume:w,cancel:g,reset:P,get isRunning(){return a&&!c},get count(){return x}}}function re(e,t){let[n,l]=typeof e=="function"?[0,e]:[h(e),t],o=null,i=null,s=0,f=a=>{a-s>=n?(l(...i),o=null):o=requestAnimationFrame(f)};return(...a)=>{i=a,s=performance.now(),o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(f)}}function oe(e,t=0){let n=!1,l=null,o=0;return(...i)=>{l=i,n||(n=!0,requestAnimationFrame(function s(){o>=t?(e(...l),o=0,n=!1):(o++,requestAnimationFrame(s))}))}}function le(e,{timeout:t}={}){return new Promise((n,l)=>{let o=performance.now(),i=t?h(t):null,s=f=>{if(e())return n();if(i&&f-o>=i)return l(new Error("waitForRaf timed out"));requestAnimationFrame(s)};requestAnimationFrame(s)})}export{H as after,te as afterRaf,Y as debounce,re as debounceRaf,K as every,ne as everyRaf,V as flow,h as parseDuration,ee as retry,X as throttle,oe as throttleRaf,Z as waitFor,le as waitForRaf};
|
|
2
|
+
function k(e){if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`Expected a finite number of ms, got: ${e}`);return e}if(typeof e!="string")throw new TypeError(`Expected a duration string or number, got ${typeof e}`);let n=e.toLowerCase().trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!n)throw new Error(`Invalid duration format: "${e}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let i=Number(n[1]);if(!Number.isFinite(i))throw new TypeError(`Invalid duration value: "${n[1]}"`);let o=n[2];switch(o){case"ms":return i;case"s":return i*1e3;case"m":return i*6e4;case"h":return i*36e5;default:throw new Error(`Unsupported duration unit: "${o}"`)}}var I;typeof performance<"u"&&typeof performance.now=="function"?I=()=>performance.now():I=()=>Date.now();var W=class{#s;#o=null;#e;#n=null;#t=!1;#r=!1;#i=!1;constructor(r){this.#s=k(r),this.#e=this.#s}get isRunning(){return this.#t}get isPaused(){return this.#r}get isFinished(){return this.#i}pause(){if(!this.#t)return;clearTimeout(this.#n),this.#n=null;let r=I()-this.#o;this.#e=Math.max(0,this.#e-r),this.#t=!1,this.#r=!0}resume(r,n=null){if(this.#i||this.#t)return;let i=n??this.#e;if(!Number.isFinite(i)||i<0)return;let o=Math.max(0,i);this.#e=o,this.#o=I(),this.#t=!0,this.#r=!1,this.#n=setTimeout(()=>{this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0,r?.()},o)}cancel(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#t=!1,this.#r=!1,this.#i=!0,this.#e=0}reset(){this.#n&&clearTimeout(this.#n),this.#n=null,this.#o=null,this.#e=this.#s,this.#t=!1,this.#r=!1,this.#i=!1}};var L;typeof DOMException<"u"?L=(e="Aborted")=>new DOMException(e,"AbortError"):L=(e="Aborted")=>{let r=new Error(e);return r.name="AbortError",r};function C(e,r){return e?e.aborted?(r(),()=>{}):(e.addEventListener("abort",r,{once:!0}),()=>e.removeEventListener("abort",r)):()=>{}}function $(e,r){let n=null;return{add(){n||(n=C(e,r))},remove(){n&&(n(),n=null)},reset(){n&&n(),n=null}}}var U=class extends W{#s=null;#o=null;#e=()=>{};constructor(r,n,{onFinish:i,signal:o}={}){super(r),this.#s=o??null,this.#o=()=>this.cancel(),this.#n(),!this.isFinished&&this.resume(()=>{this.#t(),n?.(),i?.()})}#n(){if(!(!this.#s||!this.#o)){if(this.#s.aborted){super.cancel(),this.#t();return}this.#e=C(this.#s,this.#o)}}#t(){this.#e(),this.#e=()=>{},this.#o=null}cancel(){this.isFinished||(this.#t(),super.cancel())}reset(){this.#e(),this.#e=()=>{},this.#o=()=>this.cancel(),super.reset(),this.#n()}};var Q=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function q(e,r,n,i=0){let o,l,f;if(typeof e=="function"?(o=e,Q(r)?(l=i,f=r):(l=r,f=Q(n)?n:{})):(l=e,o=r,f=Q(n)?n:{}),typeof o!="function")throw new TypeError(`Expected a function as one argument, got: ${typeof o}`);let a=l??i;if(a==null)throw new TypeError("Expected a duration (string/number) for delay");let s=k(a);return{fn:o,delay:s,options:f}}function V(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,void 0);return new U(o,i,l)}var z=class{#s;#o;#e;#n=0;#t=!1;#r=null;#i=null;#l=()=>{};constructor(r,n,{max:i=1/0,runImmediately:o=!1,signal:l}={}){if(this.#s=k(r),this.#o=n,this.#e=i,this.#i=l??null,!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l();return}if(this.#i?.aborted){this.#t=!0,this.#l();return}this.#l=C(this.#i,()=>this.cancel()),o?this.#f():this.#u()}get count(){return this.#n}get isRunning(){return!this.#t&&!!this.#r&&this.#r.isRunning}get isPaused(){return!this.#t&&!!this.#r&&this.#r.isPaused}get isFinished(){return this.#t}#a=()=>{this.#r?.cancel(),this.#r=null,this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null};#f=()=>{if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#o?.(this.#n++),this.#n>=this.#e){this.#a();return}this.#u()}};#u(){if(!this.#t){if(this.#i?.aborted){this.#a();return}this.#r=new W(this.#s),this.#r.resume(this.#f)}}pause(){this.#t||this.#r?.pause()}resume(){if(!this.#t){if(this.#i?.aborted){this.#a();return}if(this.#n>=this.#e){this.#a();return}if(this.#r){this.#r.isPaused?this.#r.resume(this.#f):this.#r.isRunning||this.#u();return}this.#u()}}cancel(){this.#t||this.#a()}reset(r=!1){if(this.#r?.cancel(),this.#r=null,this.#n=0,this.#t=!1,this.#i?.aborted){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}if(r){if(!(this.#e>0)&&this.#e!==1/0){this.#t=!0,this.#l(),this.#l=()=>{},this.#i=null;return}this.#u()}}};function X(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,void 0);return new z(o,i,l)}function at({signal:e}={}){let r=[],n=new Map,i=0,o=!1,l=!1,f=!1,a=!1,s=!1,c=1/0,p=0,b=null,h=null,y=null,m=[],u=!1,x=null,w=null,d,A=$(e,()=>d.cancel()),v=t=>{t&&t.controller&&(t.controller=null)},F=()=>{let t=r[i];t?.controller?.cancel?.(),t&&(t.controller=null)},T=()=>{a||f||(o=!1,l=!1,a=!0,F(),A.remove(),b?.())},R=()=>{f||(o=!1,l=!1,a=!1,f=!0,F(),A.remove())},E=(t,g)=>{if(R(),h){try{h(t,{step:g,index:i})}catch{}return}throw t},D=(t,g)=>{try{return t()}catch(M){E(M,g);return}},P=t=>{v(t),i+=1,queueMicrotask(_)};function _(){if(f||l||a)return;if(e?.aborted){R();return}if(y){let g=n.get(y);if(typeof g=="number")i=g;else{D(()=>{throw new Error(`Label "${y}" not found`)},r[i]);return}y=null}if(m.length>0){let g=m.shift();D(g,r[i])||(u=!0)}if(u){let g=r[i];if(!g||g.type==="label")u=!1;else return P(g)}let t=r[i];if(!t||i>=r.length){s&&++p<c?(i=0,_()):T();return}if(t.type==="label")return P(t);if(t.type==="after"){t.controller=V(()=>D(t.fn,t),t.duration,{signal:e,onFinish:()=>P(t)});return}if(t.type==="every"){if(!(t.times>0)&&t.times!==1/0)return P(t);let g=0,M=X(()=>{if(!(l||f||a)){if(e?.aborted){R();return}if(t.whileCondition&&!D(t.whileCondition,t)||(D(()=>t.fn(g++),t),t.doWhileCondition&&!D(t.doWhileCondition,t))||g>=t.times)return M.cancel(),P(t)}},t.duration,{max:t.times,signal:e});t.controller=M}}return d={after(t,g){return r.push({type:"after",duration:t,fn:g,controller:null}),d},every(t,g,M=1/0){let N=typeof M=="number"?M:M?.max??1/0,S=N===1/0?1/0:Math.max(0,N|0);return r.push({type:"every",duration:t,fn:g,times:S,whileCondition:x,doWhileCondition:w,controller:null}),x=null,w=null,d},loop(t=!0){return s=!0,c=t===!0?1/0:t,d},onFinish(t){return b=t,d},onError(t){return h=t,d},start(){return F(),f=!1,a=!1,l=!1,o=!0,i=0,p=0,A.reset(),e?.aborted||A.add(),e?.aborted?(R(),d):(_(),d)},pause(){l||f||a||(l=!0,r[i]?.controller?.pause?.())},resume(){if(!(!l||f||a)){if(e?.aborted){R();return}l=!1,r[i]?.controller?.resume?.()}},cancel(){R()},reset(){return R(),r.length=0,n.clear(),i=0,p=0,b=null,h=null,y=null,m=[],u=!1,x=null,w=null,o=!1,l=!1,f=!1,a=!1,d},label(t){return n.set(t,r.length),r.push({type:"label",name:t,controller:null}),d},jumpTo(t){return y=t,d},if(t){return m.push(()=>typeof t=="function"?!!t():!!t),d},unless(t){return m.push(()=>typeof t=="function"?!t():!t),d},while(t){return x=()=>typeof t=="function"?!!t():!!t,d},doWhile(t){return w=()=>typeof t=="function"?!!t():!!t,d},get isRunning(){return o&&!l&&!f&&!a},get isPaused(){return l},get isCancelled(){return f},get isFinished(){return a}},d}function ut(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,void 0),f=l?.signal,a=l?.trailing??!0,s=Math.max(0,o),c=-1/0,p=0,b=null,h=null,y=$(f,()=>u()),m=()=>{if(!b)return;let d=b,A=h;b=null,h=null,y.remove(),i.apply(A,d)},u=()=>{p&&clearTimeout(p),p=0,b=null,h=null,y.remove()},x=d=>{y.add(),p=setTimeout(()=>{p=0,c=I(),m()},d)},w=function(...d){if(f?.aborted)return;let A=I(),v=A-c;if(b=d,h=this,v>=s){c=A,p&&(clearTimeout(p),p=0,y.remove()),m();return}if(a&&!p){let F=Math.max(0,s-v);x(F)}};return w.cancel=u,w.flush=()=>{p&&(clearTimeout(p),p=0,c=I(),m())},f?.aborted&&u(),w}function ft(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,0),f=l?.signal,a=Math.max(0,o),s=0,c=null,p=null,b=$(f,()=>y()),h=()=>{if(!c)return;let u=c,x=p;c=null,p=null,b.remove(),i.apply(x,u)},y=()=>{s&&clearTimeout(s),s=0,c=null,p=null,b.remove()},m=function(...u){f?.aborted||(c=u,p=this,s&&clearTimeout(s),b.add(),s=setTimeout(()=>{s=0,h()},a))};return m.cancel=y,m.flush=()=>{s&&(clearTimeout(s),s=0,h())},f?.aborted&&y(),m}function ct(e,{interval:r="250ms",timeout:n,immediate:i=!1,signal:o}={}){return new Promise((l,f)=>{if(o?.aborted){f(L());return}let a=I(),s=typeof r=="string"?k(r):r,c=n!=null?k(n):null,p=null,b=()=>{p!=null&&(clearInterval(p),p=null),y()},y=C(o,()=>{b(),f(L())}),m=()=>{let u=!1;try{u=!!e()}catch(x){b(),f(x);return}if(u){b(),l();return}c!=null&&I()-a>=c&&(b(),f(new Error("waitFor timed out")))};i&&m(),p=setInterval(m,s)})}async function ht(e,{attempts:r=3,delay:n="500ms",backoff:i=!1,factor:o=2,maxDelay:l,jitter:f=!1,signal:a,random:s=Math.random,shouldRetry:c,onRetry:p}={}){if(typeof e!="function")throw new TypeError("retry: fn must be a function");let b=Math.max(1,r|0);if(a?.aborted)throw L();let h=k(n),y=l!=null?k(l):1/0,m=Math.min(h,y);for(let u=0;u<b;u++){if(a?.aborted)throw L();try{return await e(u)}catch(x){if(u===b-1||c&&!await c(x,u))throw x;let d=i?h*Math.pow(o,u):h,A=mt({expDelay:d,baseDelay:h,maxDelayMs:y,jitter:f,random:s,prevSleep:m});m=A,p&&await p(x,u,A),await pt(A,a)}}throw new Error("retry: exhausted attempts unexpectedly")}function mt({expDelay:e,baseDelay:r,maxDelayMs:n,jitter:i,random:o,prevSleep:l}){let f=Math.min(e,n);if(!i)return f;let a=i===!0?"full":i;if(a==="full")return Math.min(n,Y(0,f,o));if(a==="equal"){let s=f/2;return Math.min(n,s+Y(0,s,o))}if(a==="decorrelated"){let s=Y(r,l*3,o);return Math.min(n,s)}return f}function Y(e,r,n){let i=n(),o=Number.isFinite(i)?Math.min(1,Math.max(0,i)):0;return e+(r-e)*o}function pt(e,r){return new Promise((n,i)=>{if(r?.aborted){i(L());return}let o=0,l=()=>{o&&clearTimeout(o),o=0,a()},a=C(r,()=>{l(),i(L())});o=setTimeout(()=>{l(),n()},e)})}function j(e,r,n,i){let o=typeof n=="function"?n:void 0,l=o?i:n,{fn:f,delay:a,options:s}=q(e,r,l,void 0),{signal:c,onFinish:p}=o?{...s,onFinish:o}:s,b=Math.max(0,a),h=0,y=b,m=null,u=!1,x=!1,w=!1,d=()=>{h&&cancelAnimationFrame(h),h=0},A=()=>{},v=()=>{A(),A=()=>{}},F=()=>{d(),u=!1,x=!1,w=!0,m=null,y=0,v()},T=()=>{F(),f?.(),p?.()},R=()=>{w||F()},E=()=>{if(v(),c?.aborted){w=!0,y=0;return}A=C(c,R)};E();let D=g=>{if(!u||w)return;if(m==null&&(m=g),g-m>=y){T();return}h=requestAnimationFrame(D)},P=()=>{if(!u||w)return;d();let g=I();if(m!=null){let M=g-m;y=Math.max(0,y-M)}m=null,u=!1,x=!0},_=()=>{if(!(w||u||!x)&&!c?.aborted){if(!(y>0)){T();return}x=!1,u=!0,m=null,h=requestAnimationFrame(D)}},t=()=>{d(),m=null,y=b,u=!1,x=!1,w=!1,E()};return w?v():y>0?(u=!0,h=requestAnimationFrame(D)):T(),{pause:P,resume:_,cancel:R,reset:t,get isRunning(){return u},get isPaused(){return x},get isFinished(){return w}}}var G=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function tt(e,r,n,i,o){let l=typeof e!="function",f,a,s;l?(G(n)?s=n:G(i)?s=i:G(o)?s=o:s={},typeof n=="number"&&(f=n),typeof i=="boolean"&&(a=i),a==null&&typeof n=="boolean"&&(a=n)):s=G(n)?n:{};let{fn:c,delay:p,options:b}=q(e,r,s,void 0),h=b?.signal,y=b?.max??1/0,m=b?.runImmediately??!1,u=f??y,x=a??m,w=Math.max(0,p),d=0,A=0,v=w,F=null,T=!1,R=!1,E=!1,D=()=>{d&&cancelAnimationFrame(d),d=0},P=()=>{},_=()=>{P(),P=()=>{}},t=()=>{D(),T=!1,R=!1,E=!0,F=null,v=0,_()},g=()=>{E||t()},M=()=>{if(_(),h?.aborted){E=!0,v=0;return}P=C(h,g)};M();let N=()=>A<u,S=()=>(c?.(A++),N()?!0:(t(),!1)),H=O=>{if(!T||E)return;if(h?.aborted){t();return}if(!N()){t();return}F==null&&(F=O);let K=O-F;F=O,v-=K;let Z=Math.max(0,w);if(Z===0){v=0,S(),d=requestAnimationFrame(H);return}for(;v<=0&&!E;){if(!S())return;v+=Z}d=requestAnimationFrame(H)},J=()=>{if(!E){if(h?.aborted){t();return}if(!N()){t();return}T=!0,R=!1,F=null,d=requestAnimationFrame(H)}},ot=()=>{if(!T||E)return;D();let O=I();if(F!=null){let K=O-F;v=Math.max(0,v-K)}F=null,T=!1,R=!0},st=()=>{if(!(E||T||!R)&&!h?.aborted){if(!N()){t();return}J()}},lt=(O=!1)=>{if(D(),A=0,v=w,F=null,T=!1,R=!1,E=!1,M(),!E){if(!(u>0)&&u!==1/0){t();return}if(O){if(x&&N()&&(S(),E))return;J()}}};return E?_():!(u>0)&&u!==1/0?t():(x&&N()&&S(),E||(v=Math.max(0,w),J())),{pause:ot,resume:st,cancel:g,reset:lt,get isRunning(){return T},get isPaused(){return R},get isFinished(){return E},get count(){return A}}}function et(e,r,n){let{fn:i,delay:o,options:l}=q(e,r,n,0),f=Math.max(0,o),a=l?.signal,s=0,c=null,p=null,b=0,h=()=>{s&&cancelAnimationFrame(s),s=0},y=$(a,()=>m()),m=()=>{h(),c=null,p=null,b=0,y.remove()},u=()=>{if(!c)return;let d=c,A=p;c=null,p=null,y.remove(),i.apply(A,d)},x=d=>{if(!s)return;if(!c){m();return}if(d-b>=f){h(),u();return}s=requestAnimationFrame(x)},w=function(...d){a?.aborted||(c=d,p=this,b=I(),y.add(),h(),s=requestAnimationFrame(x))};return w.cancel=m,w.flush=()=>{!s||!c||(h(),u())},a?.aborted&&m(),w}var rt=e=>e!=null&&typeof e=="object"&&!Array.isArray(e);function nt(e,r=0,n){if(typeof e!="function")throw new TypeError(`Expected a function, got: ${typeof e}`);let i=typeof r=="number"?r:0,o=rt(r)?r:rt(n)?n:{},l=o.signal,f=o.trailing??!0,a=Math.max(0,i|0),s=!1,c=0,p=null,b=null,h=a,y=$(l,()=>u()),m=()=>{s=!1,c&&cancelAnimationFrame(c),c=0,h=a,p=null,b=null,y.remove()},u=()=>{m()},x=()=>{if(!p)return;let T=p,R=b;p=null,b=null,y.remove(),e.apply(R,T)},w=()=>{s=!1,c=0,h=a,x()},d=()=>{if(s){if(l?.aborted){u();return}if(h===0){w();return}h-=1,c=requestAnimationFrame(d)}},A=()=>{if(s){if(l?.aborted){u();return}w()}},v=a===0?()=>{s=!0,y.add(),c=requestAnimationFrame(A)}:()=>{s=!0,h=a,y.add(),c=requestAnimationFrame(d)},F=function(...T){l?.aborted||((!s||f)&&(p=T,b=this),!s&&v())};return F.cancel=u,F.flush=()=>{if(s){if(l?.aborted){u();return}s=!1,c&&cancelAnimationFrame(c),c=0,h=a,x()}},l?.aborted&&u(),F}function it(e,{timeout:r,signal:n,immediate:i=!1}={}){return new Promise((o,l)=>{if(typeof e!="function"){l(new TypeError(`waitForRaf: condition must be a function, got: ${typeof e}`));return}if(n?.aborted){l(L());return}let f=r!=null?Math.max(0,k(r)):null,a=0,s=null,c=()=>{a&&cancelAnimationFrame(a),a=0,b()},b=C(n,()=>{c(),l(L())}),h=()=>{try{return!!e()}catch(m){return c(),l(m),null}};if(i){let m=h();if(m===null)return;if(m){c(),o();return}if(f===0){c(),l(new Error("waitForRaf timed out"));return}}let y=m=>{s==null&&(s=m);let u=h();if(u!==null){if(u){c(),o();return}if(f!=null&&m-s>=f){c(),l(new Error("waitForRaf timed out"));return}a=requestAnimationFrame(y)}};a=requestAnimationFrame(y)})}function dt(){if(typeof requestAnimationFrame!="function")throw new Error("requestAnimationFrame is not available in this environment. Use the non-RAF timers (after/every/waitFor) in Node, or provide a RAF polyfill.")}var B=e=>(...r)=>(dt(),e(...r)),yt=B(j),bt=B(tt),wt=B(et),xt=B(nt),At=B(it);export{V as after,yt as afterRaf,ft as debounce,wt as debounceRaf,X as every,bt as everyRaf,at as flow,k as parseDuration,ht as retry,ut as throttle,xt as throttleRaf,ct as waitFor,At as waitForRaf};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "timeout-flow",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.18",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Fluent, composable, pauseable JavaScript timers and time control flows — plus RAF utilities for frame-based logic.",
|
|
6
6
|
"keywords": [
|
|
@@ -47,6 +47,7 @@
|
|
|
47
47
|
"types": "./types/index.d.ts",
|
|
48
48
|
"scripts": {
|
|
49
49
|
"dev": "serve testing",
|
|
50
|
+
"test:node": "node testing/node-harness.mjs",
|
|
50
51
|
"build": "node build.js",
|
|
51
52
|
"types": "tsc",
|
|
52
53
|
"prepub": "npm run build && npm run types"
|
package/src/AfterTimer.js
CHANGED
|
@@ -1,21 +1,82 @@
|
|
|
1
1
|
// ./src/AfterTimer.js
|
|
2
2
|
import { TimerBase } from './TimerBase.js';
|
|
3
|
+
import { attachAbort } from './abort.js';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Executes a function once after a delay.
|
|
6
7
|
*/
|
|
7
8
|
export class AfterTimer extends TimerBase {
|
|
9
|
+
/** @type {AbortSignal | null} */
|
|
10
|
+
#signal = null;
|
|
11
|
+
|
|
12
|
+
/** @type {(() => void) | null} */
|
|
13
|
+
#onAbort = null;
|
|
14
|
+
|
|
15
|
+
/** @type {() => void} */
|
|
16
|
+
#cleanupAbort = () => { };
|
|
17
|
+
|
|
8
18
|
/**
|
|
9
19
|
* @param {string|number} duration - Delay before firing (e.g., '1s', 300)
|
|
10
20
|
* @param {Function} fn - Main function to execute
|
|
11
|
-
* @param {
|
|
21
|
+
* @param {Object} [options]
|
|
22
|
+
* @param {Function} [options.onFinish] - Optional callback when done
|
|
23
|
+
* @param {AbortSignal} [options.signal] - Optional AbortSignal to auto-cancel
|
|
12
24
|
*/
|
|
13
|
-
constructor(duration, fn, onFinish) {
|
|
25
|
+
constructor(duration, fn, { onFinish, signal } = {}) {
|
|
14
26
|
super(duration);
|
|
27
|
+
|
|
28
|
+
this.#signal = signal ?? null;
|
|
29
|
+
this.#onAbort = () => this.cancel();
|
|
30
|
+
|
|
31
|
+
this.#attachAbort();
|
|
32
|
+
|
|
33
|
+
// If already aborted, #attachAbort() will have canceled us.
|
|
34
|
+
if (this.isFinished) return;
|
|
35
|
+
|
|
15
36
|
this.resume(() => {
|
|
37
|
+
this.#cleanupAbortListener();
|
|
16
38
|
fn?.();
|
|
17
39
|
onFinish?.();
|
|
18
40
|
});
|
|
19
41
|
}
|
|
20
|
-
}
|
|
21
42
|
|
|
43
|
+
#attachAbort() {
|
|
44
|
+
if (!this.#signal || !this.#onAbort) return;
|
|
45
|
+
|
|
46
|
+
// If already aborted, terminate immediately.
|
|
47
|
+
if (this.#signal.aborted) {
|
|
48
|
+
super.cancel();
|
|
49
|
+
this.#cleanupAbortListener();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
this.#cleanupAbort = attachAbort(this.#signal, this.#onAbort);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#cleanupAbortListener() {
|
|
57
|
+
this.#cleanupAbort();
|
|
58
|
+
this.#cleanupAbort = () => { };
|
|
59
|
+
|
|
60
|
+
// Keep signal reference so reset() can reattach.
|
|
61
|
+
this.#onAbort = null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
cancel() {
|
|
65
|
+
if (this.isFinished) return;
|
|
66
|
+
|
|
67
|
+
// Remove listener first to avoid keeping instance alive.
|
|
68
|
+
this.#cleanupAbortListener();
|
|
69
|
+
|
|
70
|
+
super.cancel();
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
reset() {
|
|
74
|
+
// Preserve AbortSignal semantics.
|
|
75
|
+
this.#cleanupAbort();
|
|
76
|
+
this.#cleanupAbort = () => { };
|
|
77
|
+
this.#onAbort = () => this.cancel();
|
|
78
|
+
|
|
79
|
+
super.reset();
|
|
80
|
+
this.#attachAbort();
|
|
81
|
+
}
|
|
82
|
+
}
|