timeout-flow 0.0.19 → 0.1.0

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 CHANGED
@@ -1,307 +1,475 @@
1
- # timeout-flow
2
-
3
- [![npm](https://img.shields.io/npm/v/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
4
- [![downloads](https://img.shields.io/npm/dm/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
5
- [![bundle size](https://img.shields.io/bundlephobia/minzip/timeout-flow)](https://bundlephobia.com/package/timeout-flow)
6
- [![license](https://img.shields.io/npm/l/timeout-flow)](https://github.com/iWhatty/TimeoutFlow-js/blob/main/LICENSE)
7
- [![stars](https://img.shields.io/github/stars/iWhatty/TimeoutFlow-js?style=social)](https://github.com/iWhatty/TimeoutFlow-js)
8
-
9
- Fluent, human-readable time control for JavaScript. A modern, composable upgrade to `setTimeout` and `setInterval` with chaining, conditional logic, pause/resume control, retries, and RAF utilities.
10
-
11
- ## Features
12
-
13
- - Readable durations: `"1s"`, `"500ms"`, plain numbers
14
- - Pause / resume / cancel controllers for `after()`, `every()`, RAF variants
15
- - `flow()` builds declarative timelines with branching and labels
16
- - `retry()` with backoff, jitter, and `AbortSignal` cancellation
17
- - `waitFor()` polls a predicate with timeout
18
- - RAF variants (`afterRaf`, `everyRaf`, `debounceRaf`, `throttleRaf`, `waitForRaf`) for frame-aligned timing
19
- - ESM-first, tree-shakeable. Per-file subpath exports for size-sensitive consumers (~1.2 KB gzipped for a single primitive)
20
- - Zero dependencies
21
- - ~6–7 KB minified for the full kit (~2–3 KB gzipped)
22
-
23
- ---
24
-
25
- ## Install
26
-
27
- ```sh
28
- pnpm add timeout-flow
29
- ```
30
-
31
- ---
32
-
33
- ## Quick start
34
-
35
- ```js
36
- import { after } from 'timeout-flow';
37
-
38
- function greet() {
39
- console.log('Hello');
40
- }
41
-
42
- const ctrl = after('2s', greet);
43
-
44
- ctrl.pause();
45
- ctrl.resume();
46
- ctrl.cancel();
47
- ```
48
-
49
- ---
50
-
51
- ## API
52
-
53
- ### `after(duration, fn, options?)`
54
-
55
- Run once after a delay.
56
-
57
- ```js
58
- import { after } from 'timeout-flow';
59
-
60
- after('2s', function greet() {
61
- console.log('Hello');
62
- });
63
- ```
64
-
65
- ### `every(duration, fn, options?)`
66
-
67
- Repeat execution with optional limit.
68
-
69
- ```js
70
- import { every } from 'timeout-flow';
71
-
72
- const ticker = every('1s', function tick(i) {
73
- console.log('Tick', i);
74
- }, { max: 5 });
75
- ```
76
-
77
- ### `debounce(duration, fn, options?)`
78
-
79
- Delay execution until inactivity.
80
-
81
- ```js
82
- import { debounce } from 'timeout-flow';
83
-
84
- const debouncedSearch = debounce('300ms', function search(event) {
85
- console.log('Searching for:', event.target.value);
86
- });
87
-
88
- debouncedSearch.cancel();
89
- debouncedSearch.flush();
90
- ```
91
-
92
- ### `throttle(duration, fn, options?)`
93
-
94
- Limit execution frequency.
95
-
96
- ```js
97
- import { throttle } from 'timeout-flow';
98
-
99
- const onScroll = throttle('250ms', function handleScroll() {
100
- console.log('scroll');
101
- });
102
-
103
- onScroll.cancel();
104
- onScroll.flush();
105
- ```
106
-
107
- ### `retry(fn, options?)`
108
-
109
- Retry async operations with backoff and jitter.
110
-
111
- ```js
112
- import { retry } from 'timeout-flow';
113
-
114
- await retry(async function fetchData() {
115
- return fetch('/api/data');
116
- }, {
117
- attempts: 5,
118
- delay: '500ms',
119
- backoff: true,
120
- factor: 2,
121
- maxDelay: '5s',
122
- jitter: 'decorrelated'
123
- });
124
- ```
125
-
126
- ### `waitFor(predicate, options?)`
127
-
128
- Wait until a condition becomes true.
129
-
130
- ```js
131
- import { waitFor } from 'timeout-flow';
132
-
133
- await waitFor(function checkLoaded() {
134
- return document.querySelector('#loaded');
135
- }, {
136
- interval: '250ms',
137
- timeout: '5s',
138
- immediate: true
139
- });
140
- ```
141
-
142
- ### `flow()`
143
-
144
- Build declarative time flows.
145
-
146
- ```js
147
- import { flow } from 'timeout-flow';
148
-
149
- flow()
150
- .after('1s', function stepOne() {
151
- console.log('Step 1');
152
- })
153
- .every('500ms', function tick(i) {
154
- console.log('Tick', i);
155
- }, { max: 3 })
156
- .after('1s', function finalStep() {
157
- console.log('Final Step');
158
- })
159
- .start();
160
- ```
161
-
162
- Flow reads like a timeline and keeps duration-first ordering for readability.
163
-
164
- ### RAF utilities
165
-
166
- Frame-based timing powered by `requestAnimationFrame`. Ideal for visual updates, scroll handlers, layout checks, and animation loops.
167
-
168
- Available: `afterRaf()`, `everyRaf()`, `debounceRaf()`, `throttleRaf()`, `waitForRaf()`.
169
-
170
- ```js
171
- import { throttleRaf } from 'timeout-flow';
172
-
173
- const onScroll = throttleRaf(function drawFrame() {
174
- console.log('draw');
175
- });
176
-
177
- onScroll.cancel();
178
- onScroll.flush();
179
- ```
180
-
181
- ### Controllers
182
-
183
- Most time-based primitives return a controller object:
184
-
185
- ```js
186
- const ctrl = after('1s', () => console.log('done'));
187
-
188
- ctrl.pause();
189
- ctrl.resume();
190
- ctrl.cancel();
191
- ctrl.reset?.();
192
-
193
- console.log(ctrl.isRunning);
194
- console.log(ctrl.isPaused);
195
- console.log(ctrl.isFinished);
196
- ```
197
-
198
- Shared by `after()`, `every()`, `afterRaf()`, `everyRaf()`. All controllers are pause-safe (paused time does not count), cancel-safe, monotonic-time based, and `AbortSignal`-aware where supported.
199
-
200
- ### AbortSignal support
201
-
202
- Many utilities accept `{ signal }` for automatic cancellation.
203
-
204
- ```js
205
- import { after } from 'timeout-flow';
206
-
207
- const ac = new AbortController();
208
-
209
- after('2s', function doWork() {
210
- console.log('Will not run if aborted');
211
- }, { signal: ac.signal });
212
-
213
- ac.abort();
214
- ```
215
-
216
- If already aborted at creation time, no work is scheduled.
217
-
218
- ### Public surface
219
-
220
- ```js
221
- import {
222
- after,
223
- every,
224
- debounce,
225
- throttle,
226
- retry,
227
- waitFor,
228
- flow,
229
-
230
- afterRaf,
231
- everyRaf,
232
- debounceRaf,
233
- throttleRaf,
234
- waitForRaf
235
- } from 'timeout-flow';
236
- ```
237
-
238
- ---
239
-
240
- ## Notes
241
-
242
- ### Tree-shaking and per-primitive imports
243
-
244
- Two import styles, same package, choose by bundle-size sensitivity:
245
-
246
- ```js
247
- // Full kit. Every primitive available on one import.
248
- // Modern bundlers (esbuild, vite, rollup, webpack 5) will tree-shake
249
- // unused exports because the package ships `sideEffects: false` and the
250
- // `.` entrypoint points at ESM source instead of a pre-minified blob.
251
- import { after, debounce, retry } from 'timeout-flow';
252
- ```
253
-
254
- ```js
255
- // Per-primitive subpath. Explicit minimum surface, useful when you know
256
- // you only need one primitive and want the bundle to reflect that
257
- // without relying on the bundler's tree-shaker. Same source either way.
258
- import { after } from 'timeout-flow/after';
259
- import { every } from 'timeout-flow/every';
260
- import { debounce } from 'timeout-flow/debounce';
261
- import { throttle } from 'timeout-flow/throttle';
262
- import { retry } from 'timeout-flow/retry';
263
- import { waitFor } from 'timeout-flow/wait-for';
264
- import { flow } from 'timeout-flow/flow';
265
- import { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from 'timeout-flow/raf';
266
- import { parseDuration } from 'timeout-flow/parse-duration';
267
- ```
268
-
269
- Measured for a single `after()` call in a typical browser bundler (esbuild, minified + gzip):
270
-
271
- | Import style | Gzip |
272
- |---|---:|
273
- | pre-0.0.19 default (full minified bundle) | 5098 bytes |
274
- | 0.0.19 default (`import { after } from 'timeout-flow'`) | 1199 bytes |
275
- | 0.0.19 subpath (`import { after } from 'timeout-flow/after'`) | 1199 bytes |
276
-
277
- For unbundled `<script type="module">` consumption of the full kit, use the **`timeout-flow/min`** subpath, which points at the pre-built minified IIFE.
278
-
279
- ### Clean signatures
280
-
281
- timeout-flow supports both natural-language and function-first argument ordering:
282
-
283
- ```js
284
- after('1s', done);
285
- // or
286
- after(done, '1s');
287
- ```
288
-
289
- This applies to `after()`, `every()`, `debounce()`, `throttle()`. Use whichever reads best in your codebase.
290
-
291
- ### Philosophy
292
-
293
- timeout-flow is not just a wrapper around timers, it's a composable toolkit for expressing time as readable logic. Temporal behavior should be:
294
-
295
- - **Readable.** Durations like `"1s"` and `"500ms"` beat magic numbers.
296
- - **Composable.** Sequencing should be declarative.
297
- - **Controllable.** Timers should pause, resume, cancel.
298
- - **Branchable.** Real flows need `if`, `while`, `label`, `jumpTo()`.
299
- - **Tiny.** No runtime bloat.
300
-
301
- > Think of timeout-flow as `setTimeout()` with superpowers.
302
-
303
- ---
304
-
305
- ## License
306
-
307
- Licensed under AGPL-3.0 with WATT3D Additional Terms. See [LICENSE](./LICENSE) and [ADDITIONAL_TERMS.md](./ADDITIONAL_TERMS.md). Commercial AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.
1
+ # timeout-flow
2
+
3
+ [![npm](https://badgen.net/npm/v/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
4
+ [![downloads](https://badgen.net/npm/dm/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
5
+ [![license](https://badgen.net/static/license/AGPL-3.0%20%2B%20terms/blue)](https://github.com/iWhatty/timeout-flow/blob/main/LICENSE)
6
+ [![stars](https://badgen.net/github/stars/iWhatty/timeout-flow)](https://github.com/iWhatty/timeout-flow)
7
+ [![types](https://badgen.net/npm/types/timeout-flow)](https://www.npmjs.com/package/timeout-flow)
8
+
9
+ Fluent, human-readable time control for JavaScript. A modern, composable upgrade to `setTimeout` and `setInterval` with chaining, conditional logic, pause/resume control, retries, and RAF utilities.
10
+
11
+ ## Features
12
+
13
+ - Readable durations: `"1s"`, `"500ms"`, plain numbers
14
+ - Pause / resume / cancel controllers for `after()`, `every()`, RAF variants
15
+ - `flow()` builds declarative timelines with branching and labels
16
+ - `sleep()` promise delay with `AbortSignal` cancellation
17
+ - `retry()` with fixed/linear/exponential backoff, jitter, deadlines, result predicates and hooks
18
+ - `waitFor()` polls a sync or async predicate with an exact timeout
19
+ - RAF variants (`afterRaf`, `everyRaf`, `debounceRaf`, `throttleRaf`, `waitForRaf`) for frame-aligned timing
20
+ - ESM-first, tree-shakeable. Per-file subpath exports for size-sensitive consumers (~1.2 KB gzipped for a single primitive)
21
+ - Zero dependencies
22
+ - ~15 KB minified for the full kit (~5.5 KB gzipped)
23
+
24
+ ---
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ pnpm add timeout-flow
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Quick start
35
+
36
+ ```js
37
+ import { after } from 'timeout-flow';
38
+
39
+ function greet() {
40
+ console.log('Hello');
41
+ }
42
+
43
+ const ctrl = after('2s', greet);
44
+
45
+ ctrl.pause();
46
+ ctrl.resume();
47
+ ctrl.cancel();
48
+ ```
49
+
50
+ ---
51
+
52
+ ## API
53
+
54
+ ### `parseDuration(input)`
55
+
56
+ Convert a finite number of milliseconds or a duration string to milliseconds.
57
+ Strings support `ms`, `s`, `m`, and `h`, decimal values, case-insensitive units,
58
+ and surrounding whitespace. Invalid strings and non-finite numbers throw.
59
+ Negative numbers are accepted; negative strings are not.
60
+
61
+ ### `after(duration, fn, options?)`
62
+
63
+ Run once after a delay.
64
+
65
+ ```js
66
+ import { after } from 'timeout-flow';
67
+
68
+ after('2s', function greet() {
69
+ console.log('Hello');
70
+ });
71
+ ```
72
+
73
+ ### `every(duration, fn, options?)`
74
+
75
+ Repeat execution with optional limit.
76
+
77
+ ```js
78
+ import { every } from 'timeout-flow';
79
+
80
+ const ticker = every('1s', function tick(i) {
81
+ console.log('Tick', i);
82
+ }, { max: 5 });
83
+ ```
84
+
85
+ ### `debounce(duration, fn, options?)`
86
+
87
+ Delay execution until inactivity.
88
+
89
+ ```js
90
+ import { debounce } from 'timeout-flow';
91
+
92
+ const debouncedSearch = debounce('300ms', function search(event) {
93
+ console.log('Searching for:', event.target.value);
94
+ });
95
+
96
+ debouncedSearch.cancel();
97
+ debouncedSearch.flush();
98
+ ```
99
+
100
+ ### `throttle(duration, fn, options?)`
101
+
102
+ Limit execution frequency.
103
+
104
+ ```js
105
+ import { throttle } from 'timeout-flow';
106
+
107
+ const onScroll = throttle('250ms', function handleScroll() {
108
+ console.log('scroll');
109
+ });
110
+
111
+ onScroll.cancel();
112
+ onScroll.flush();
113
+ ```
114
+
115
+ ### `sleep(duration?, options?)`
116
+
117
+ Promise-based delay with the same duration format as everything else.
118
+
119
+ ```js
120
+ import { sleep } from 'timeout-flow';
121
+
122
+ await sleep('500ms');
123
+ await sleep(250);
124
+
125
+ // Cancelable: rejects with signal.reason (an AbortError by default)
126
+ // and clears its timer.
127
+ const ac = new AbortController();
128
+ await sleep('10s', { signal: ac.signal });
129
+ ```
130
+
131
+ * Numbers behave like `setTimeout`: `NaN` and negative values wait 0 ms.
132
+ * Huge values (including `Infinity`) are capped at ~24.8 days instead of
133
+ overflowing and firing immediately.
134
+ * Invalid strings (e.g. `'soon'`) reject; `sleep()` never throws synchronously.
135
+
136
+ ### `retry(fn, options?)`
137
+
138
+ Retry sync or async work with delays, backoff, jitter, deadlines and hooks.
139
+
140
+ ```js
141
+ import { retry } from 'timeout-flow';
142
+
143
+ async function fetchData() {
144
+ return fetch('/api/data');
145
+ }
146
+
147
+ await retry(fetchData, {
148
+ attempts: 5,
149
+ delay: '500ms',
150
+ backoff: true,
151
+ factor: 2,
152
+ maxDelay: '5s',
153
+ jitter: 'decorrelated'
154
+ });
155
+ ```
156
+
157
+ | Option | Default | Meaning |
158
+ | --- | --- | --- |
159
+ | `attempts` | `3` | Total attempts including the first. `Infinity` is allowed (pair it with `timeout`). |
160
+ | `delay` | `'500ms'` | Base delay between attempts. |
161
+ | `backoff` | `false` | `false`/`'fixed'`, `'linear'` (`delay * (n+1)`), `true`/`'exponential'` (`delay * factor^n`). |
162
+ | `factor` | `2` | Exponential multiplier. |
163
+ | `maxDelay` | none | Cap applied to every computed delay. |
164
+ | `jitter` | `false` | `true`/`'full'`, `'equal'`, `'decorrelated'`, or a number `j` in `[0, 1]` for proportional ±j jitter (`delay * (1 + (random()*2 - 1) * j)`, applied after the `maxDelay` cap and re-capped by it, never below 0). Other numbers or `NaN` reject with a `RangeError` before any attempt. `delayFirst` is never jittered. Delays are rounded to whole ms. |
165
+ | `delayFirst` | `false` | Wait before the first attempt: `true` uses `delay`, or pass a duration. |
166
+ | `timeout` | none | Overall deadline from the call. No retry starts after it; an in-flight attempt is not interrupted and the first attempt always runs. |
167
+ | `isSuccess(result, attempt)` | none | Return `false` to treat a resolved result as a failure and retry. |
168
+ | `shouldRetry(error, attempt)` | none | Return `false` to stop retrying. |
169
+ | `onAttempt(attempt, elapsedMs)` | none | Called before every attempt. |
170
+ | `onRetry(error, attempt, delayMs)` | none | Called after deciding to retry, before waiting. |
171
+ | `signal` | none | Abort waiting and further attempts. |
172
+ | `sleep(ms, { signal })` | built-in `sleep` | Injectable wait, e.g. for fake-timer tests. |
173
+ | `now()` | `performance.now` | Injectable clock used for `timeout`. |
174
+ | `random()` | `Math.random` | Injectable RNG for jitter. |
175
+
176
+ Attempt numbers are **0-based** everywhere (`fn(attempt)`, hooks, predicates).
177
+
178
+ Outcome:
179
+
180
+ * Resolves with the first successful result.
181
+ * Otherwise rejects with the **last failure**: the last thrown error as-is, or,
182
+ if the last attempt resolved with a result `isSuccess` rejected, an error
183
+ with `name: 'RetryError'`, `.result` (that last result) and `.attempts`.
184
+ * On abort, rejects with `signal.reason` (an `AbortError` by default).
185
+
186
+ #### Retry recipes
187
+
188
+ Retry until a result looks right, with a little log line per attempt:
189
+
190
+ ```js
191
+ const response = await retry(() => sendMessage(tabId, msg), {
192
+ attempts: 4,
193
+ delay: 200,
194
+ backoff: 'exponential',
195
+ maxDelay: '2s',
196
+ isSuccess: (res) => res?.ok === true,
197
+ onAttempt: (attempt, elapsed) => console.debug('attempt', attempt, Math.round(elapsed), 'ms'),
198
+ });
199
+ ```
200
+
201
+ Exponential backoff with ±15% proportional jitter:
202
+
203
+ ```js
204
+ await retry(poll, {
205
+ attempts: 5,
206
+ delay: 200,
207
+ backoff: true,
208
+ factor: 1.6,
209
+ maxDelay: '1500ms',
210
+ jitter: 0.15, // each wait lands within 85%..115% of its computed delay
211
+ });
212
+ ```
213
+
214
+ Time-bounded retry (deadline instead of an attempt count):
215
+
216
+ ```js
217
+ await retry(() => connect(), {
218
+ attempts: Infinity,
219
+ delay: '250ms',
220
+ timeout: '5s',
221
+ });
222
+ ```
223
+
224
+ Give something a moment to settle before the first try, and stop on fatal errors:
225
+
226
+ ```js
227
+ await retry(loadConfig, {
228
+ delayFirst: '100ms',
229
+ attempts: 3,
230
+ backoff: 'linear',
231
+ shouldRetry: (err) => err.name !== 'SyntaxError',
232
+ });
233
+ ```
234
+
235
+ Return a result object instead of throwing:
236
+
237
+ ```js
238
+ const outcome = await retry(task, { attempts: 3 }).then(
239
+ (value) => ({ ok: true, value }),
240
+ (error) => ({ ok: false, error, value: error?.result })
241
+ );
242
+ ```
243
+
244
+ Deterministic tests without real timers:
245
+
246
+ ```js
247
+ let clock = 0;
248
+ const waits = [];
249
+
250
+ await retry(task, {
251
+ attempts: 4,
252
+ delay: 100,
253
+ backoff: true,
254
+ now: () => clock,
255
+ sleep: async (ms) => { waits.push(ms); clock += ms; },
256
+ }).catch(() => {});
257
+
258
+ // waits -> [100, 200, 400]
259
+ ```
260
+
261
+ ### `waitFor(predicate, options?)`
262
+
263
+ Wait until a condition becomes truthy. Resolves with the condition's value.
264
+
265
+ ```js
266
+ import { waitFor } from 'timeout-flow';
267
+
268
+ const el = await waitFor(function findLoaded() {
269
+ return document.querySelector('#loaded');
270
+ }, {
271
+ interval: '250ms',
272
+ timeout: '5s',
273
+ immediate: true
274
+ });
275
+ ```
276
+
277
+ Timing model:
278
+
279
+ * The first check runs after `interval` unless `immediate: true`.
280
+ * Conditions may be async; the next check is scheduled `interval` after the
281
+ previous one settles, so checks never overlap.
282
+ * `timeout` is measured from the call and has its own timer, so it is not
283
+ rounded up to the next poll. At the deadline a sync condition gets one final
284
+ check, so success at exactly `timeout` counts (`elapsed >= timeout` times out
285
+ only if the condition is still falsy). It rejects with an `Error` named
286
+ `'TimeoutError'` (message `'waitFor timed out'`).
287
+ * `signal` rejects with `signal.reason`.
288
+
289
+ `waitForRaf()` checks once per animation frame and measures `timeout` from the
290
+ first frame's timestamp (RAF time), timing out once `elapsed >= timeout`.
291
+
292
+ ### `flow(options?)`
293
+
294
+ Build declarative time flows. Accepts `{ signal }` for cancellation.
295
+
296
+ ```js
297
+ import { flow } from 'timeout-flow';
298
+
299
+ flow()
300
+ .after('1s', function stepOne() {
301
+ console.log('Step 1');
302
+ })
303
+ .every('500ms', function tick(i) {
304
+ console.log('Tick', i);
305
+ }, { max: 3 })
306
+ .after('1s', function finalStep() {
307
+ console.log('Final Step');
308
+ })
309
+ .start();
310
+ ```
311
+
312
+ Flow reads like a timeline and keeps duration-first ordering for readability.
313
+
314
+ ### RAF utilities
315
+
316
+ Frame-based timing powered by `requestAnimationFrame`. Ideal for visual updates, scroll handlers, layout checks, and animation loops.
317
+
318
+ Available: `afterRaf()`, `everyRaf()`, `debounceRaf()`, `throttleRaf()`, `waitForRaf()`.
319
+
320
+ ```js
321
+ import { throttleRaf } from 'timeout-flow';
322
+
323
+ const onScroll = throttleRaf(function drawFrame() {
324
+ console.log('draw');
325
+ });
326
+
327
+ onScroll.cancel();
328
+ onScroll.flush();
329
+ ```
330
+
331
+ The RAF timers and debounce accept both `(duration, fn, options?)` and
332
+ `(fn, duration, options?)`; `debounceRaf(fn, options?)` defaults to 0 ms.
333
+ `everyRaf` accepts `max` and `runImmediately`. `throttleRaf(fn, frameSkip?, options?)`
334
+ runs after `frameSkip + 1` frames, using the latest arguments by default;
335
+ `{ trailing: false }` keeps the first call instead. RAF debounce and throttle
336
+ provide `cancel()` and `flush()`. `waitForRaf(condition, { timeout, signal, immediate })`
337
+ requires a synchronous condition and resolves with `undefined`, not its value.
338
+ RAF utilities require a browser RAF implementation or a polyfill.
339
+ `afterRaf` with a zero or negative duration invokes its callback synchronously.
340
+
341
+ ### Controllers
342
+
343
+ Most time-based primitives return a controller object:
344
+
345
+ ```js
346
+ const ctrl = after('1s', () => console.log('done'));
347
+
348
+ ctrl.pause();
349
+ ctrl.resume();
350
+ ctrl.cancel();
351
+ ctrl.reset();
352
+
353
+ console.log(ctrl.isRunning);
354
+ console.log(ctrl.isPaused);
355
+ console.log(ctrl.isFinished);
356
+ ```
357
+
358
+ `reset()` stops the controller without restarting it; `every()` and `everyRaf()`
359
+ also accept `reset(true)` to restart. After `after().reset()`, call `resume()`
360
+ to run again.
361
+
362
+ Shared by `after()`, `every()`, `afterRaf()`, `everyRaf()`. All controllers are pause-safe (paused time does not count), cancel-safe, monotonic-time based, and `AbortSignal`-aware where supported.
363
+
364
+ ### AbortSignal support
365
+
366
+ Many utilities accept `{ signal }` for automatic cancellation.
367
+
368
+ ```js
369
+ import { after } from 'timeout-flow';
370
+
371
+ const ac = new AbortController();
372
+
373
+ after('2s', function doWork() {
374
+ console.log('Will not run if aborted');
375
+ }, { signal: ac.signal });
376
+
377
+ ac.abort();
378
+ ```
379
+
380
+ If already aborted at creation time, no work is scheduled.
381
+
382
+ ### Public surface
383
+
384
+ ```js
385
+ import {
386
+ parseDuration,
387
+ after,
388
+ every,
389
+ debounce,
390
+ throttle,
391
+ sleep,
392
+ retry,
393
+ waitFor,
394
+ flow,
395
+
396
+ afterRaf,
397
+ everyRaf,
398
+ debounceRaf,
399
+ throttleRaf,
400
+ waitForRaf
401
+ } from 'timeout-flow';
402
+ ```
403
+
404
+ ---
405
+
406
+ ## Notes
407
+
408
+ ### Tree-shaking and per-primitive imports
409
+
410
+ Two import styles, same package, choose by bundle-size sensitivity:
411
+
412
+ ```js
413
+ // Full kit. Every primitive available on one import.
414
+ // Modern bundlers (esbuild, vite, rollup, webpack 5) will tree-shake
415
+ // unused exports because the package ships `sideEffects: false` and the
416
+ // `.` entrypoint points at ESM source instead of a pre-minified blob.
417
+ import { after, debounce, retry } from 'timeout-flow';
418
+ ```
419
+
420
+ ```js
421
+ // Per-primitive subpath. Explicit minimum surface, useful when you know
422
+ // you only need one primitive and want the bundle to reflect that
423
+ // without relying on the bundler's tree-shaker. Same source either way.
424
+ import { after } from 'timeout-flow/after';
425
+ import { every } from 'timeout-flow/every';
426
+ import { debounce } from 'timeout-flow/debounce';
427
+ import { throttle } from 'timeout-flow/throttle';
428
+ import { sleep } from 'timeout-flow/sleep';
429
+ import { retry } from 'timeout-flow/retry';
430
+ import { waitFor } from 'timeout-flow/wait-for';
431
+ import { flow } from 'timeout-flow/flow';
432
+ import { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from 'timeout-flow/raf';
433
+ import { parseDuration } from 'timeout-flow/parse-duration';
434
+ ```
435
+
436
+ Measured for a single `after()` call in a typical browser bundler (esbuild, minified + gzip):
437
+
438
+ | Import style | Gzip |
439
+ |---|---:|
440
+ | pre-0.0.19 default (full minified bundle) | 5098 bytes |
441
+ | 0.0.19 default (`import { after } from 'timeout-flow'`) | 1199 bytes |
442
+ | 0.0.19 subpath (`import { after } from 'timeout-flow/after'`) | 1199 bytes |
443
+
444
+ For unbundled `<script type="module">` consumption of the full kit, use the **`timeout-flow/min`** subpath, which points at the pre-built minified ESM bundle.
445
+
446
+ ### Clean signatures
447
+
448
+ timeout-flow supports both natural-language and function-first argument ordering:
449
+
450
+ ```js
451
+ after('1s', done);
452
+ // or
453
+ after(done, '1s');
454
+ ```
455
+
456
+ This applies to `after()`, `every()`, `debounce()`, `throttle()`. Use whichever reads best in your codebase.
457
+ The function-first form also accepts `(fn, options?)`, defaulting the delay to 0 ms.
458
+
459
+ ### Philosophy
460
+
461
+ timeout-flow is not just a wrapper around timers, it's a composable toolkit for expressing time as readable logic. Temporal behavior should be:
462
+
463
+ - **Readable.** Durations like `"1s"` and `"500ms"` beat magic numbers.
464
+ - **Composable.** Sequencing should be declarative.
465
+ - **Controllable.** Timers should pause, resume, cancel.
466
+ - **Branchable.** Real flows need `if`, `while`, `label`, `jumpTo()`.
467
+ - **Tiny.** No runtime bloat.
468
+
469
+ > Think of timeout-flow as `setTimeout()` with superpowers.
470
+
471
+ ---
472
+
473
+ ## License
474
+
475
+ Licensed under AGPL-3.0 with WATT3D Additional Terms. See [LICENSE](./LICENSE) and [ADDITIONAL_TERMS.md](./ADDITIONAL_TERMS.md). Commercial AI/model-training use requires compliance with those terms or a separate WATT3D license. © WATT3D.