timeout-flow 0.0.18 → 0.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,77 @@
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
- });
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
77
  }