timeout-flow 0.0.19 → 0.0.20

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/src/throttle.js CHANGED
@@ -1,142 +1,142 @@
1
- // ./src/throttle.js
2
-
3
- import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
4
- import { pendingAbort } from './abort.js';
5
- import { now } from './now.js'
6
-
7
-
8
- /**
9
- * @typedef {((...args: any[]) => void) & {
10
- * cancel: () => void,
11
- * flush: () => void
12
- * }} ThrottledFunction
13
- */
14
-
15
- /**
16
- * Creates a throttled version of a function.
17
- * Executes immediately, throttles further calls, optional trailing execution.
18
- *
19
- * Preferred:
20
- * - throttle(fn, delay, [options])
21
- *
22
- * Also supported:
23
- * - throttle(delay, fn, [options]) // legacy/alt ordering
24
- *
25
- * Notes:
26
- * - Uses performance.now() (via `now()`) for elapsed timing.
27
- * - If trailing is enabled, uses the latest arguments/context seen during the wait.
28
- * - `.cancel()` clears any pending trailing invocation.
29
- * - `.flush()` immediately invokes a pending trailing call (if scheduled).
30
- * - Optional AbortSignal: abort cancels any pending trailing invocation.
31
- *
32
- * @param {Function|string|number} a
33
- * @param {Function|string|number|Object} b
34
- * @param {Object} [c]
35
- * @param {boolean} [c.trailing=true]
36
- * @param {AbortSignal} [c.signal]
37
- * @returns {ThrottledFunction}
38
- */
39
- export function throttle(a, b, c) {
40
- // Require an explicit delay by passing `undefined` as defaultDelay.
41
- const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
42
-
43
- const signal = options?.signal;
44
- const trailing = options?.trailing ?? true;
45
-
46
- const waitWindow = Math.max(0, delay);
47
-
48
- let lastCallTime = -Infinity;
49
- let timeoutId = 0;
50
-
51
- /** @type {any[] | null} */
52
- let lastArgs = null;
53
- /** @type {any | null} */
54
- let lastThis = null;
55
-
56
- const abort = pendingAbort(signal, () => cancel());
57
-
58
- const invoke = () => {
59
- if (!lastArgs) return;
60
-
61
- const args = lastArgs;
62
- const ctx = lastThis;
63
-
64
- // clear first (re-entrancy safe + GC friendly)
65
- lastArgs = null;
66
- lastThis = null;
67
-
68
- abort.remove();
69
- fn.apply(ctx, args);
70
- };
71
-
72
- const cancel = () => {
73
- if (timeoutId) clearTimeout(timeoutId);
74
- timeoutId = 0;
75
-
76
- lastArgs = null;
77
- lastThis = null;
78
-
79
- abort.remove();
80
- };
81
-
82
- /** @param {number} wait */
83
- const scheduleTrailing = (wait) => {
84
- abort.add();
85
-
86
- timeoutId = setTimeout(() => {
87
- timeoutId = 0;
88
- lastCallTime = now();
89
- invoke();
90
- }, wait);
91
- };
92
-
93
- /** @type {any} */
94
- const throttled = function (...args) {
95
- if (signal?.aborted) return;
96
-
97
- const currentTime = now();
98
- const timeSinceLast = currentTime - lastCallTime;
99
-
100
- lastArgs = args;
101
- lastThis = this;
102
-
103
- if (timeSinceLast >= waitWindow) {
104
- // Leading edge: run now
105
- lastCallTime = currentTime;
106
-
107
- // Clear any pending trailing call (and listener)
108
- if (timeoutId) {
109
- clearTimeout(timeoutId);
110
- timeoutId = 0;
111
- abort.remove();
112
- }
113
-
114
- invoke();
115
- return;
116
- }
117
-
118
- if (!trailing) return;
119
-
120
- // Trailing edge: schedule once, keep latest args
121
- if (!timeoutId) {
122
- const wait = Math.max(0, waitWindow - timeSinceLast);
123
- scheduleTrailing(wait);
124
- }
125
- };
126
-
127
- throttled.cancel = cancel;
128
-
129
- throttled.flush = () => {
130
- if (!timeoutId) return;
131
- clearTimeout(timeoutId);
132
- timeoutId = 0;
133
-
134
- lastCallTime = now();
135
- invoke();
136
- };
137
-
138
- // If already aborted at creation time, ensure clean slate.
139
- if (signal?.aborted) cancel();
140
-
141
- return throttled;
1
+ // ./src/throttle.js
2
+
3
+ import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
4
+ import { pendingAbort } from './abort.js';
5
+ import { now } from './now.js'
6
+
7
+
8
+ /**
9
+ * @typedef {((...args: any[]) => void) & {
10
+ * cancel: () => void,
11
+ * flush: () => void
12
+ * }} ThrottledFunction
13
+ */
14
+
15
+ /**
16
+ * Creates a throttled version of a function.
17
+ * Executes immediately, throttles further calls, optional trailing execution.
18
+ *
19
+ * Preferred:
20
+ * - throttle(fn, delay, [options])
21
+ *
22
+ * Also supported:
23
+ * - throttle(delay, fn, [options]) // legacy/alt ordering
24
+ *
25
+ * Notes:
26
+ * - Uses performance.now() (via `now()`) for elapsed timing.
27
+ * - If trailing is enabled, uses the latest arguments/context seen during the wait.
28
+ * - `.cancel()` clears any pending trailing invocation.
29
+ * - `.flush()` immediately invokes a pending trailing call (if scheduled).
30
+ * - Optional AbortSignal: abort cancels any pending trailing invocation.
31
+ *
32
+ * @param {Function|string|number} a
33
+ * @param {Function|string|number|Object} b
34
+ * @param {Object} [c]
35
+ * @param {boolean} [c.trailing=true]
36
+ * @param {AbortSignal} [c.signal]
37
+ * @returns {ThrottledFunction}
38
+ */
39
+ export function throttle(a, b, c) {
40
+ // Require an explicit delay by passing `undefined` as defaultDelay.
41
+ const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
42
+
43
+ const signal = options?.signal;
44
+ const trailing = options?.trailing ?? true;
45
+
46
+ const waitWindow = Math.max(0, delay);
47
+
48
+ let lastCallTime = -Infinity;
49
+ let timeoutId = 0;
50
+
51
+ /** @type {any[] | null} */
52
+ let lastArgs = null;
53
+ /** @type {any | null} */
54
+ let lastThis = null;
55
+
56
+ const abort = pendingAbort(signal, () => cancel());
57
+
58
+ const invoke = () => {
59
+ if (!lastArgs) return;
60
+
61
+ const args = lastArgs;
62
+ const ctx = lastThis;
63
+
64
+ // clear first (re-entrancy safe + GC friendly)
65
+ lastArgs = null;
66
+ lastThis = null;
67
+
68
+ abort.remove();
69
+ fn.apply(ctx, args);
70
+ };
71
+
72
+ const cancel = () => {
73
+ if (timeoutId) clearTimeout(timeoutId);
74
+ timeoutId = 0;
75
+
76
+ lastArgs = null;
77
+ lastThis = null;
78
+
79
+ abort.remove();
80
+ };
81
+
82
+ /** @param {number} wait */
83
+ const scheduleTrailing = (wait) => {
84
+ abort.add();
85
+
86
+ timeoutId = setTimeout(() => {
87
+ timeoutId = 0;
88
+ lastCallTime = now();
89
+ invoke();
90
+ }, wait);
91
+ };
92
+
93
+ /** @type {any} */
94
+ const throttled = function (...args) {
95
+ if (signal?.aborted) return;
96
+
97
+ const currentTime = now();
98
+ const timeSinceLast = currentTime - lastCallTime;
99
+
100
+ lastArgs = args;
101
+ lastThis = this;
102
+
103
+ if (timeSinceLast >= waitWindow) {
104
+ // Leading edge: run now
105
+ lastCallTime = currentTime;
106
+
107
+ // Clear any pending trailing call (and listener)
108
+ if (timeoutId) {
109
+ clearTimeout(timeoutId);
110
+ timeoutId = 0;
111
+ abort.remove();
112
+ }
113
+
114
+ invoke();
115
+ return;
116
+ }
117
+
118
+ if (!trailing) return;
119
+
120
+ // Trailing edge: schedule once, keep latest args
121
+ if (!timeoutId) {
122
+ const wait = Math.max(0, waitWindow - timeSinceLast);
123
+ scheduleTrailing(wait);
124
+ }
125
+ };
126
+
127
+ throttled.cancel = cancel;
128
+
129
+ throttled.flush = () => {
130
+ if (!timeoutId) return;
131
+ clearTimeout(timeoutId);
132
+ timeoutId = 0;
133
+
134
+ lastCallTime = now();
135
+ invoke();
136
+ };
137
+
138
+ // If already aborted at creation time, ensure clean slate.
139
+ if (signal?.aborted) cancel();
140
+
141
+ return throttled;
142
142
  }
package/src/waitFor.js CHANGED
@@ -1,77 +1,96 @@
1
- // ./src/waitFor.js
2
-
3
- import { parseDuration } from './parseDuration.js';
4
- import { attachAbort, createAbortError } from './abort.js';
5
- import { now } from './now.js'
6
-
7
-
8
- /**
9
- * Waits for a condition to become true, polling at intervals.
10
- *
11
- * @param {Function} condition - returns truthy when satisfied
12
- * @param {Object} [options] - optional polling control
13
- * @param {string|number} [options.interval='250ms'] - poll frequency
14
- * @param {string|number} [options.timeout] - max wait time
15
- * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately
16
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
17
- * @returns {Promise<void>}
18
- */
19
- export function waitFor(condition, { interval = '250ms', timeout, immediate = false, signal } = {}) {
20
- return new Promise((resolve, reject) => {
21
- if (signal?.aborted) {
22
- reject(createAbortError());
23
- return;
24
- }
25
-
26
- const start = now();
27
-
28
- const intervalMs = typeof interval === 'string' ? parseDuration(interval) : interval;
29
- const timeoutMs = timeout != null ? parseDuration(timeout) : null;
30
-
31
- let poller = null;
32
-
33
- const cleanup = () => {
34
- if (poller != null) {
35
- clearInterval(poller);
36
- poller = null;
37
- }
38
- cleanupAbort();
39
- };
40
-
41
- const onAbort = () => {
42
- cleanup();
43
- reject(createAbortError());
44
- };
45
-
46
- const cleanupAbort = attachAbort(signal, onAbort);
47
-
48
- const check = () => {
49
- let ok = false;
50
-
51
- try {
52
- ok = !!condition();
53
- } catch (err) {
54
- cleanup();
55
- reject(err);
56
- return;
57
- }
58
-
59
- if (ok) {
60
- cleanup();
61
- resolve();
62
- return;
63
- }
64
-
65
- if (timeoutMs != null && now() - start >= timeoutMs) {
66
- cleanup();
67
- reject(new Error('waitFor timed out'));
68
- }
69
- };
70
-
71
- // Only evaluate immediately if explicitly requested
72
- if (immediate) check();
73
-
74
- // Schedule exactly once
75
- poller = setInterval(check, intervalMs);
76
- });
77
- }
1
+ // ./src/waitFor.js
2
+
3
+ import { attachAbort, abortReason } from './abort.js';
4
+ import { toDelay } from './sleep.js';
5
+
6
+
7
+ /**
8
+ * Waits for a condition to become truthy, polling at intervals.
9
+ *
10
+ * Timing model:
11
+ * - With `immediate: false` (default) the first check runs after `interval`.
12
+ * - The next check is scheduled `interval` after the previous one finishes,
13
+ * so async conditions never overlap.
14
+ * - `timeout` is measured from the call and enforced by its own timer, so it
15
+ * is not rounded up to the next poll. At the deadline a sync condition gets
16
+ * one final check (success at exactly `timeout` counts, like `>=`); an async
17
+ * check still pending at the deadline is abandoned and the promise rejects.
18
+ *
19
+ * @template T
20
+ * @param {() => T | Promise<T>} condition - sync or async; truthy when satisfied
21
+ * @param {Object} [options] - optional polling control
22
+ * @param {string|number} [options.interval='250ms'] - delay between checks
23
+ * @param {string|number} [options.timeout] - max wait time; rejects with an
24
+ * Error named 'TimeoutError' (message 'waitFor timed out')
25
+ * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately
26
+ * @param {AbortSignal} [options.signal] - rejects with `signal.reason` on abort
27
+ * @returns {Promise<T>} resolves with the condition's truthy value
28
+ */
29
+ export function waitFor(condition, { interval = '250ms', timeout, immediate = false, signal } = {}) {
30
+ return new Promise((resolve, reject) => {
31
+ if (signal?.aborted) {
32
+ reject(abortReason(signal));
33
+ return;
34
+ }
35
+
36
+ const intervalMs = toDelay(interval);
37
+ const timeoutMs = timeout != null ? toDelay(timeout) : null;
38
+
39
+ let done = false;
40
+ let pending = false;
41
+ let poller = 0;
42
+ let deadline = 0;
43
+
44
+ const finish = (settle, value) => {
45
+ if (done) return;
46
+ done = true;
47
+ clearTimeout(poller);
48
+ clearTimeout(deadline);
49
+ cleanupAbort();
50
+ settle(value);
51
+ };
52
+
53
+ const cleanupAbort = attachAbort(signal, () => finish(reject, abortReason(signal)));
54
+
55
+ const check = async () => {
56
+ let value;
57
+ pending = true;
58
+ try {
59
+ value = await condition();
60
+ } catch (err) {
61
+ finish(reject, err);
62
+ return;
63
+ } finally {
64
+ pending = false;
65
+ }
66
+ if (done) return;
67
+ if (value) finish(resolve, value);
68
+ else poller = setTimeout(check, intervalMs);
69
+ };
70
+
71
+ if (immediate) check();
72
+ else poller = setTimeout(check, intervalMs);
73
+
74
+ if (timeoutMs != null) {
75
+ deadline = setTimeout(() => {
76
+ if (!pending) {
77
+ // Final check at the deadline (sync results only).
78
+ let value;
79
+ try {
80
+ value = condition();
81
+ } catch (err) {
82
+ finish(reject, err);
83
+ return;
84
+ }
85
+ if (value && typeof value.then !== 'function') {
86
+ finish(resolve, value);
87
+ return;
88
+ }
89
+ }
90
+ const err = new Error('waitFor timed out');
91
+ err.name = 'TimeoutError';
92
+ finish(reject, err);
93
+ }, timeoutMs);
94
+ }
95
+ });
96
+ }
package/types/abort.d.ts CHANGED
@@ -1,31 +1,40 @@
1
- /**
2
- * Attach an AbortSignal listener and return a cleanup function.
3
- * - If `signal` is missing, returns a no-op cleanup.
4
- * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
5
- *
6
- * @param {AbortSignal | null | undefined} signal
7
- * @param {() => void} onAbort
8
- * @returns {() => void} cleanup
9
- */
10
- export function attachAbort(signal: AbortSignal | null | undefined, onAbort: () => void): () => void;
11
- /**
12
- * Manage AbortSignal listener lifecycle for "pending work" cases.
13
- * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
14
- *
15
- * @param {AbortSignal | null | undefined} signal
16
- * @param {() => void} onAbort
17
- * @returns {{ add: () => void, remove: () => void, reset: () => void }}
18
- */
19
- export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: () => void): {
20
- add: () => void;
21
- remove: () => void;
22
- reset: () => void;
23
- };
24
- /**
25
- * Standardized AbortError factory.
26
- * Works in browsers and Node runtimes that may not have DOMException.
27
- *
28
- * We resolve the best implementation once at module load time.
29
- * This avoids feature detection in the hot path.
30
- */
31
- export let createAbortError: any;
1
+ /**
2
+ * Attach an AbortSignal listener and return a cleanup function.
3
+ * - If `signal` is missing, returns a no-op cleanup.
4
+ * - If already aborted, calls `onAbort()` immediately and returns a no-op cleanup.
5
+ *
6
+ * @param {AbortSignal | null | undefined} signal
7
+ * @param {() => void} onAbort
8
+ * @returns {() => void} cleanup
9
+ */
10
+ export function attachAbort(signal: AbortSignal | null | undefined, onAbort: () => void): () => void;
11
+ /**
12
+ * Manage AbortSignal listener lifecycle for "pending work" cases.
13
+ * Call `add()` when work becomes pending and `remove()` when it’s resolved/canceled.
14
+ *
15
+ * @param {AbortSignal | null | undefined} signal
16
+ * @param {() => void} onAbort
17
+ * @returns {{ add: () => void, remove: () => void, reset: () => void }}
18
+ */
19
+ export function pendingAbort(signal: AbortSignal | null | undefined, onAbort: () => void): {
20
+ add: () => void;
21
+ remove: () => void;
22
+ reset: () => void;
23
+ };
24
+ /**
25
+ * The error an aborted operation should reject with: the signal's own
26
+ * `reason` (what `fetch()` and other web APIs use), falling back to a
27
+ * standard AbortError for runtimes without `AbortSignal.reason`.
28
+ *
29
+ * @param {AbortSignal | null | undefined} signal
30
+ * @returns {any}
31
+ */
32
+ export function abortReason(signal: AbortSignal | null | undefined): any;
33
+ /**
34
+ * Standardized AbortError factory.
35
+ * Works in browsers and Node runtimes that may not have DOMException.
36
+ *
37
+ * We resolve the best implementation once at module load time.
38
+ * This avoids feature detection in the hot path.
39
+ */
40
+ export let createAbortError: any;
package/types/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- export { parseDuration } from "./parseDuration.js";
2
- export { flow } from "./TimeoutFlow.js";
3
- export { throttle } from "./throttle.js";
4
- export { debounce } from "./debounce.js";
5
- export { after } from "./after.js";
6
- export { every } from "./every.js";
7
- export { waitFor } from "./waitFor.js";
8
- export { retry } from "./retry.js";
9
- export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
1
+ export { parseDuration } from "./parseDuration.js";
2
+ export { flow } from "./TimeoutFlow.js";
3
+ export { throttle } from "./throttle.js";
4
+ export { debounce } from "./debounce.js";
5
+ export { after } from "./after.js";
6
+ export { every } from "./every.js";
7
+ export { sleep } from "./sleep.js";
8
+ export { waitFor } from "./waitFor.js";
9
+ export { retry } from "./retry.js";
10
+ export { afterRaf, everyRaf, debounceRaf, throttleRaf, waitForRaf } from "./raf/index.js";
@@ -1,19 +1,19 @@
1
- /**
2
- * Waits for a condition to return truthy, polling each frame.
3
- *
4
- * Timing model:
5
- * - Evaluates `condition()` once per animation frame until it returns truthy.
6
- * - If `timeout` is provided, timeout is measured in RAF time (frame timestamps).
7
- *
8
- * @param {Function} condition - Function returning truthy when complete
9
- * @param {Object} [options]
10
- * @param {string|number} [options.timeout] - Optional max time to wait
11
- * @param {AbortSignal} [options.signal] - Optional AbortSignal to cancel waiting
12
- * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
13
- * @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
14
- */
15
- export function waitForRaf(condition: Function, { timeout, signal, immediate }?: {
16
- timeout?: string | number | undefined;
17
- signal?: AbortSignal | undefined;
18
- immediate?: boolean | undefined;
19
- }): Promise<void>;
1
+ /**
2
+ * Waits for a condition to return truthy, polling each frame.
3
+ *
4
+ * Timing model:
5
+ * - Evaluates `condition()` once per animation frame until it returns truthy.
6
+ * - If `timeout` is provided, timeout is measured in RAF time (frame timestamps).
7
+ *
8
+ * @param {Function} condition - Function returning truthy when complete
9
+ * @param {Object} [options]
10
+ * @param {string|number} [options.timeout] - Optional max time to wait
11
+ * @param {AbortSignal} [options.signal] - Optional AbortSignal; rejects with `signal.reason`
12
+ * @param {boolean} [options.immediate=false] - If true, evaluate condition immediately before first frame
13
+ * @returns {Promise<void>} Resolves when condition is met, rejects on timeout/abort
14
+ */
15
+ export function waitForRaf(condition: Function, { timeout, signal, immediate }?: {
16
+ timeout?: string | number | undefined;
17
+ signal?: AbortSignal | undefined;
18
+ immediate?: boolean | undefined;
19
+ }): Promise<void>;