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/ADDITIONAL_TERMS.md +122 -122
- package/LICENSE +694 -694
- package/README.md +475 -307
- package/dist/timeout-flow.min.js +1 -1
- package/package.json +79 -68
- package/robots.txt +79 -79
- package/src/AfterTimer.js +81 -81
- package/src/EveryTimer.js +208 -208
- package/src/TimeoutFlow.js +400 -400
- package/src/TimerBase.js +137 -132
- package/src/abort.js +87 -75
- package/src/after.js +32 -32
- package/src/debounce.js +105 -105
- package/src/every.js +34 -34
- package/src/index.js +24 -23
- package/src/now.js +22 -22
- package/src/parseDuration.js +43 -46
- package/src/raf/ReadMe-Raf.md +94 -94
- package/src/raf/afterRaf.js +203 -203
- package/src/raf/debounceRaf.js +126 -126
- package/src/raf/everyRaf.js +314 -316
- package/src/raf/index.js +27 -27
- package/src/raf/throttleRaf.js +181 -181
- package/src/raf/waitForRaf.js +100 -100
- package/src/resolveDelayAndFn.js +65 -89
- package/src/retry.js +205 -164
- package/src/sleep.js +58 -0
- package/src/throttle.js +141 -141
- package/src/waitFor.js +99 -77
- package/types/TimerBase.d.ts +2 -2
- package/types/abort.d.ts +9 -0
- package/types/index.d.ts +1 -0
- package/types/raf/waitForRaf.d.ts +1 -1
- package/types/resolveDelayAndFn.d.ts +1 -15
- package/types/retry.d.ts +57 -18
- package/types/sleep.d.ts +29 -0
- package/types/waitFor.d.ts +19 -8
package/src/resolveDelayAndFn.js
CHANGED
|
@@ -1,90 +1,66 @@
|
|
|
1
|
-
// ./src/resolveDelayAndFn.js
|
|
2
|
-
import { parseDuration } from './parseDuration.js';
|
|
3
|
-
|
|
4
|
-
const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Resolves flexible
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* -
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
// (fn, delay, options?)
|
|
67
|
-
delayRaw = /** @type {any} */ (b);
|
|
68
|
-
options = isPlainOptions(c) ? c : {};
|
|
69
|
-
}
|
|
70
|
-
} else {
|
|
71
|
-
// (delay, fn, options?)
|
|
72
|
-
delayRaw = /** @type {any} */ (a);
|
|
73
|
-
fn = /** @type {any} */ (b);
|
|
74
|
-
options = isPlainOptions(c) ? c : {};
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
if (typeof fn !== 'function') {
|
|
78
|
-
throw new TypeError(`Expected a function as one argument, got: ${typeof fn}`);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
const raw = delayRaw ?? defaultDelay;
|
|
82
|
-
|
|
83
|
-
// If someone passes `(fn, options)` but defaultDelay was undefined, surface a clear error.
|
|
84
|
-
if (raw == null) {
|
|
85
|
-
throw new TypeError('Expected a duration (string/number) for delay');
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const delay = parseDuration(raw);
|
|
89
|
-
return { fn, delay, options };
|
|
1
|
+
// ./src/resolveDelayAndFn.js
|
|
2
|
+
import { parseDuration } from './parseDuration.js';
|
|
3
|
+
|
|
4
|
+
export const isPlainOptions = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Resolves flexible overloads and returns `{ fn, delay, options }`.
|
|
8
|
+
*
|
|
9
|
+
* Supported forms:
|
|
10
|
+
* - (fn, delay, [options])
|
|
11
|
+
* - (delay, fn, [options])
|
|
12
|
+
* - (fn, [options]) // delay defaults
|
|
13
|
+
*
|
|
14
|
+
* This is intentionally strict about what counts as "options" to avoid
|
|
15
|
+
* treating random values as configuration.
|
|
16
|
+
*
|
|
17
|
+
* @template {Record<string, any>} O
|
|
18
|
+
* @param {Function|string|number} a
|
|
19
|
+
* @param {Function|string|number|O} b
|
|
20
|
+
* @param {O} [c]
|
|
21
|
+
* @param {string|number} [defaultDelay=0]
|
|
22
|
+
* @returns {{ fn: Function, delay: number, options: O }}
|
|
23
|
+
*/
|
|
24
|
+
export function resolveDelayFnOptions(a, b, c, defaultDelay = 0) {
|
|
25
|
+
/** @type {Function} */
|
|
26
|
+
let fn;
|
|
27
|
+
|
|
28
|
+
/** @type {string|number|undefined} */
|
|
29
|
+
let delayRaw;
|
|
30
|
+
|
|
31
|
+
/** @type {any} */
|
|
32
|
+
let options;
|
|
33
|
+
|
|
34
|
+
if (typeof a === 'function') {
|
|
35
|
+
fn = a;
|
|
36
|
+
|
|
37
|
+
if (isPlainOptions(b)) {
|
|
38
|
+
// (fn, options)
|
|
39
|
+
delayRaw = defaultDelay;
|
|
40
|
+
options = b;
|
|
41
|
+
} else {
|
|
42
|
+
// (fn, delay, options?)
|
|
43
|
+
delayRaw = /** @type {any} */ (b);
|
|
44
|
+
options = isPlainOptions(c) ? c : {};
|
|
45
|
+
}
|
|
46
|
+
} else {
|
|
47
|
+
// (delay, fn, options?)
|
|
48
|
+
delayRaw = /** @type {any} */ (a);
|
|
49
|
+
fn = /** @type {any} */ (b);
|
|
50
|
+
options = isPlainOptions(c) ? c : {};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (typeof fn !== 'function') {
|
|
54
|
+
throw new TypeError(`Expected a function as one argument, got: ${typeof fn}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const raw = delayRaw ?? defaultDelay;
|
|
58
|
+
|
|
59
|
+
// If someone passes `(fn, options)` but defaultDelay was undefined, surface a clear error.
|
|
60
|
+
if (raw == null) {
|
|
61
|
+
throw new TypeError('Expected a duration (string/number) for delay');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const delay = parseDuration(raw);
|
|
65
|
+
return { fn, delay, options };
|
|
90
66
|
}
|
package/src/retry.js
CHANGED
|
@@ -1,164 +1,205 @@
|
|
|
1
|
-
// ./src/retry.js
|
|
2
|
-
import { parseDuration } from './parseDuration.js';
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* @
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
1
|
+
// ./src/retry.js
|
|
2
|
+
import { parseDuration } from './parseDuration.js';
|
|
3
|
+
import { abortReason } from './abort.js';
|
|
4
|
+
import { now as defaultNow } from './now.js';
|
|
5
|
+
import { sleep as defaultSleep, toDelay } from './sleep.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Retries a (possibly async) function with delays between attempts.
|
|
9
|
+
*
|
|
10
|
+
* Attempt numbers are 0-based everywhere (`fn`, hooks, predicates).
|
|
11
|
+
*
|
|
12
|
+
* Outcome:
|
|
13
|
+
* - Resolves with the first successful result.
|
|
14
|
+
* - When retries stop (attempts exhausted, `timeout` reached, or
|
|
15
|
+
* `shouldRetry` returned false) it rejects with the last failure:
|
|
16
|
+
* the last thrown error as-is, or, when the last attempt resolved with a
|
|
17
|
+
* result rejected by `isSuccess`, a `RetryError` (`name: 'RetryError'`)
|
|
18
|
+
* carrying `.result` and `.attempts`.
|
|
19
|
+
* - On abort it rejects with `signal.reason` (an AbortError by default).
|
|
20
|
+
*
|
|
21
|
+
* @template T
|
|
22
|
+
* @param {(attempt: number) => T | Promise<T>} fn - sync or async function
|
|
23
|
+
* @param {Object} [options]
|
|
24
|
+
* @param {number} [options.attempts=3] - total attempts including the first (`Infinity` allowed)
|
|
25
|
+
* @param {string|number} [options.delay='500ms'] - base delay between attempts
|
|
26
|
+
* @param {boolean|'fixed'|'linear'|'exponential'} [options.backoff=false]
|
|
27
|
+
* Delay growth per retry n (0-based): fixed (false) = delay,
|
|
28
|
+
* linear = delay*(n+1), exponential (true) = delay*factor^n.
|
|
29
|
+
* @param {number} [options.factor=2] - exponential multiplier
|
|
30
|
+
* @param {string|number} [options.maxDelay] - cap for each computed delay
|
|
31
|
+
* @param {boolean|number|'full'|'equal'|'decorrelated'} [options.jitter=false] - jitter strategy.
|
|
32
|
+
* A number j in [0, 1] applies proportional �j jitter:
|
|
33
|
+
* delay * (1 + (random()*2 - 1) * j), after the maxDelay cap and then
|
|
34
|
+
* re-capped by maxDelay, clamped to >= 0 and rounded. Other numbers
|
|
35
|
+
* (or NaN) reject with a RangeError before any attempt.
|
|
36
|
+
* `delayFirst` is never jittered.
|
|
37
|
+
* @param {boolean|string|number} [options.delayFirst=false]
|
|
38
|
+
* Wait before the first attempt (`true` = `delay`, or an explicit duration).
|
|
39
|
+
* @param {string|number} [options.timeout] - overall deadline measured from the call.
|
|
40
|
+
* A retry is skipped when its wait would end past the deadline; the first
|
|
41
|
+
* attempt always runs and an in-flight attempt is never interrupted.
|
|
42
|
+
* @param {AbortSignal} [options.signal] - cancels waiting and further attempts
|
|
43
|
+
* @param {(result: T, attempt: number) => boolean | Promise<boolean>} [options.isSuccess]
|
|
44
|
+
* Treat a resolved result as a failure (and retry) when this returns false.
|
|
45
|
+
* @param {(err: any, attempt: number) => boolean | Promise<boolean>} [options.shouldRetry]
|
|
46
|
+
* Return false to stop retrying after a failure.
|
|
47
|
+
* @param {(attempt: number, elapsedMs: number) => void | Promise<void>} [options.onAttempt]
|
|
48
|
+
* Called before every attempt.
|
|
49
|
+
* @param {(err: any, attempt: number, delayMs: number) => void | Promise<void>} [options.onRetry]
|
|
50
|
+
* Called after deciding to retry and before waiting.
|
|
51
|
+
* @param {(ms: number, options: { signal?: AbortSignal }) => Promise<void>} [options.sleep]
|
|
52
|
+
* Injectable sleep (e.g. for fake-timer tests).
|
|
53
|
+
* @param {() => number} [options.now] - injectable clock used for `timeout`
|
|
54
|
+
* @param {() => number} [options.random=Math.random] - injectable RNG for tests
|
|
55
|
+
* @returns {Promise<T>}
|
|
56
|
+
*/
|
|
57
|
+
export async function retry(
|
|
58
|
+
fn,
|
|
59
|
+
{
|
|
60
|
+
attempts = 3,
|
|
61
|
+
delay = '500ms',
|
|
62
|
+
backoff = false,
|
|
63
|
+
factor = 2,
|
|
64
|
+
maxDelay,
|
|
65
|
+
jitter = false,
|
|
66
|
+
delayFirst = false,
|
|
67
|
+
timeout,
|
|
68
|
+
signal,
|
|
69
|
+
isSuccess,
|
|
70
|
+
shouldRetry,
|
|
71
|
+
onAttempt,
|
|
72
|
+
onRetry,
|
|
73
|
+
sleep = defaultSleep,
|
|
74
|
+
now = defaultNow,
|
|
75
|
+
random = Math.random,
|
|
76
|
+
} = {}
|
|
77
|
+
) {
|
|
78
|
+
if (typeof fn !== 'function') throw new TypeError('retry: fn must be a function');
|
|
79
|
+
|
|
80
|
+
const totalAttempts = attempts === Infinity ? Infinity : Math.max(1, attempts | 0);
|
|
81
|
+
|
|
82
|
+
const throwIfAborted = () => {
|
|
83
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
84
|
+
};
|
|
85
|
+
throwIfAborted();
|
|
86
|
+
|
|
87
|
+
if (typeof jitter === 'number' && !(jitter >= 0 && jitter <= 1)) {
|
|
88
|
+
throw new RangeError(`retry: numeric jitter must be within [0, 1], got: ${jitter}`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const baseDelay = parseDuration(delay);
|
|
92
|
+
const maxDelayMs = maxDelay != null ? parseDuration(maxDelay) : Infinity;
|
|
93
|
+
const deadline = timeout != null ? parseDuration(timeout) : Infinity;
|
|
94
|
+
const mode = backoff === true ? 'exponential' : backoff || 'fixed';
|
|
95
|
+
const start = now();
|
|
96
|
+
const elapsed = () => now() - start;
|
|
97
|
+
|
|
98
|
+
const wait = async (ms) => {
|
|
99
|
+
await sleep(ms, { signal });
|
|
100
|
+
throwIfAborted(); // custom sleeps may ignore the signal
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
if (delayFirst) await wait(toDelay(delayFirst === true ? baseDelay : delayFirst));
|
|
104
|
+
|
|
105
|
+
// decorrelated jitter needs to remember prior sleep
|
|
106
|
+
let prevSleep = Math.min(baseDelay, maxDelayMs);
|
|
107
|
+
|
|
108
|
+
for (let attempt = 0; ; attempt++) {
|
|
109
|
+
throwIfAborted();
|
|
110
|
+
if (onAttempt) await onAttempt(attempt, elapsed());
|
|
111
|
+
|
|
112
|
+
let failure;
|
|
113
|
+
try {
|
|
114
|
+
const result = await fn(attempt);
|
|
115
|
+
if (!isSuccess || (await isSuccess(result, attempt))) return result;
|
|
116
|
+
failure = new RetryError(result, attempt + 1);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
failure = err;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
if (attempt + 1 >= totalAttempts) throw failure;
|
|
122
|
+
if (shouldRetry && !(await shouldRetry(failure, attempt))) throw failure;
|
|
123
|
+
|
|
124
|
+
const growth =
|
|
125
|
+
mode === 'exponential' ? Math.pow(factor, attempt) :
|
|
126
|
+
mode === 'linear' ? attempt + 1 :
|
|
127
|
+
1;
|
|
128
|
+
|
|
129
|
+
const ms = toDelay(Math.round(computeSleep({
|
|
130
|
+
expDelay: baseDelay * growth,
|
|
131
|
+
baseDelay,
|
|
132
|
+
maxDelayMs,
|
|
133
|
+
jitter,
|
|
134
|
+
random,
|
|
135
|
+
prevSleep,
|
|
136
|
+
})));
|
|
137
|
+
prevSleep = ms;
|
|
138
|
+
|
|
139
|
+
// Don't begin a wait whose next attempt would start past the deadline.
|
|
140
|
+
if (elapsed() + ms > deadline) throw failure;
|
|
141
|
+
|
|
142
|
+
if (onRetry) await onRetry(failure, attempt, ms);
|
|
143
|
+
|
|
144
|
+
await wait(ms);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Rejection used when the final attempt resolved with a result that
|
|
150
|
+
* `isSuccess` rejected. Check with `err.name === 'RetryError'`.
|
|
151
|
+
*/
|
|
152
|
+
class RetryError extends Error {
|
|
153
|
+
constructor(result, attempts) {
|
|
154
|
+
super(`retry: unsuccessful result after ${attempts} attempt(s)`);
|
|
155
|
+
this.name = 'RetryError';
|
|
156
|
+
this.result = result;
|
|
157
|
+
this.attempts = attempts;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Compute retry sleep with optional backoff clamp + jitter.
|
|
163
|
+
*
|
|
164
|
+
* Jitter strategies:
|
|
165
|
+
* - false: no jitter
|
|
166
|
+
* - 'full': random(0, cap)
|
|
167
|
+
* - 'equal': cap/2 + random(0, cap/2)
|
|
168
|
+
* - 'decorrelated': random(baseDelay, prevSleep*3) (clamped)
|
|
169
|
+
* - number j: cap * (1 � j), re-capped by maxDelay, >= 0
|
|
170
|
+
*/
|
|
171
|
+
function computeSleep({ expDelay, baseDelay, maxDelayMs, jitter, random, prevSleep }) {
|
|
172
|
+
const cap = Math.min(expDelay, maxDelayMs);
|
|
173
|
+
|
|
174
|
+
if (!jitter) return cap;
|
|
175
|
+
|
|
176
|
+
if (typeof jitter === 'number') {
|
|
177
|
+
const spread = randBetween(-1, 1, random) * jitter;
|
|
178
|
+
return Math.min(maxDelayMs, Math.max(0, cap * (1 + spread)));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const mode = jitter === true ? 'full' : jitter;
|
|
182
|
+
|
|
183
|
+
if (mode === 'full') {
|
|
184
|
+
return Math.min(maxDelayMs, randBetween(0, cap, random));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (mode === 'equal') {
|
|
188
|
+
const half = cap / 2;
|
|
189
|
+
return Math.min(maxDelayMs, half + randBetween(0, half, random));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (mode === 'decorrelated') {
|
|
193
|
+
const next = randBetween(baseDelay, prevSleep * 3, random);
|
|
194
|
+
return Math.min(maxDelayMs, next);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Unknown mode -> treat as no jitter (safe fallback)
|
|
198
|
+
return cap;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function randBetween(min, max, random) {
|
|
202
|
+
const r = random();
|
|
203
|
+
const t = Number.isFinite(r) ? Math.min(1, Math.max(0, r)) : 0;
|
|
204
|
+
return min + (max - min) * t;
|
|
205
|
+
}
|
package/src/sleep.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// ./src/sleep.js
|
|
2
|
+
import { parseDuration } from './parseDuration.js';
|
|
3
|
+
import { attachAbort, abortReason } from './abort.js';
|
|
4
|
+
|
|
5
|
+
// Largest delay setTimeout can hold; larger values overflow and fire immediately.
|
|
6
|
+
const MAX_DELAY = 2_147_483_647;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Normalizes a duration to a setTimeout-safe delay in ms.
|
|
10
|
+
* - Strings are parsed ("500ms", "1s", "1.5m", "1h"); invalid strings throw.
|
|
11
|
+
* - Numbers behave like setTimeout: NaN and negative values clamp to 0.
|
|
12
|
+
* - Values above setTimeout's 32-bit limit (including Infinity) are capped at
|
|
13
|
+
* 2147483647 ms (~24.8 days) instead of overflowing and firing immediately.
|
|
14
|
+
*
|
|
15
|
+
* @param {string|number|null|undefined} duration
|
|
16
|
+
* @returns {number}
|
|
17
|
+
*/
|
|
18
|
+
export function toDelay(duration) {
|
|
19
|
+
if (duration == null) return 0;
|
|
20
|
+
const ms = typeof duration === 'number' ? duration : parseDuration(duration);
|
|
21
|
+
return ms > 0 ? Math.min(ms, MAX_DELAY) : 0;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Promise-based delay: `await sleep('500ms')`.
|
|
26
|
+
*
|
|
27
|
+
* - Accepts the same durations as the rest of TimeoutFlow ("500ms", "1s", 250).
|
|
28
|
+
* - Numbers behave like setTimeout: NaN / negative become 0; huge values
|
|
29
|
+
* (including Infinity) are capped at ~24.8 days rather than firing at once.
|
|
30
|
+
* - Invalid duration strings reject with an Error (never throw synchronously).
|
|
31
|
+
* - With `signal`, rejects with `signal.reason` (an AbortError by default)
|
|
32
|
+
* and clears its timer; an already-aborted signal rejects immediately.
|
|
33
|
+
*
|
|
34
|
+
* @param {string|number} [duration=0]
|
|
35
|
+
* @param {Object} [options]
|
|
36
|
+
* @param {AbortSignal} [options.signal]
|
|
37
|
+
* @returns {Promise<void>}
|
|
38
|
+
*/
|
|
39
|
+
export function sleep(duration = 0, { signal } = {}) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const ms = toDelay(duration);
|
|
42
|
+
|
|
43
|
+
if (signal?.aborted) {
|
|
44
|
+
reject(abortReason(signal));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const cleanupAbort = attachAbort(signal, () => {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
reject(abortReason(signal));
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
cleanupAbort();
|
|
55
|
+
resolve();
|
|
56
|
+
}, ms);
|
|
57
|
+
});
|
|
58
|
+
}
|