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/debounce.js
CHANGED
|
@@ -1,106 +1,106 @@
|
|
|
1
|
-
// ./src/debounce.js
|
|
2
|
-
|
|
3
|
-
import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
|
|
4
|
-
import { pendingAbort } from './abort.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* @typedef {((...args: any[]) => void) & {
|
|
8
|
-
* cancel: () => void,
|
|
9
|
-
* flush: () => void
|
|
10
|
-
* }} DebouncedFunction
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Creates a debounced function that delays invoking `fn`
|
|
15
|
-
* until after `delay` ms of inactivity.
|
|
16
|
-
*
|
|
17
|
-
* Preferred:
|
|
18
|
-
* - debounce(fn, [delay], [options]) // delay defaults to 0
|
|
19
|
-
*
|
|
20
|
-
* Also supported:
|
|
21
|
-
* - debounce(delay, fn, [options]) // legacy/alt ordering
|
|
22
|
-
* - debounce(fn, [options])
|
|
23
|
-
*
|
|
24
|
-
* Notes:
|
|
25
|
-
* - Always invokes with the latest arguments/context.
|
|
26
|
-
* - `.cancel()` clears any pending invocation.
|
|
27
|
-
* - `.flush()` immediately invokes if pending.
|
|
28
|
-
* - Optional AbortSignal: abort cancels pending invocation.
|
|
29
|
-
*
|
|
30
|
-
* @param {Function|string|number} a - Function or delay (see overloads)
|
|
31
|
-
* @param {Function|string|number|Object} [b] - Delay, function, or options
|
|
32
|
-
* @param {Object} [c] - Options (3-arg form)
|
|
33
|
-
* @param {AbortSignal} [c.signal] - Optional AbortSignal to cancel pending work
|
|
34
|
-
* @returns {DebouncedFunction}
|
|
35
|
-
*/
|
|
36
|
-
export function debounce(a, b, c) {
|
|
37
|
-
const { fn, delay, options } = resolveDelayFnOptions(a, b, c, 0);
|
|
38
|
-
const signal = options?.signal;
|
|
39
|
-
|
|
40
|
-
const wait = Math.max(0, delay);
|
|
41
|
-
|
|
42
|
-
let timeoutId = 0;
|
|
43
|
-
|
|
44
|
-
/** @type {any[] | null} */
|
|
45
|
-
let lastArgs = null;
|
|
46
|
-
/** @type {any | null} */
|
|
47
|
-
let lastThis = null;
|
|
48
|
-
|
|
49
|
-
const abort = pendingAbort(signal, () => cancel());
|
|
50
|
-
|
|
51
|
-
const invoke = () => {
|
|
52
|
-
if (!lastArgs) return;
|
|
53
|
-
|
|
54
|
-
const args = lastArgs;
|
|
55
|
-
const ctx = lastThis;
|
|
56
|
-
|
|
57
|
-
// clear first (re-entrancy safe + GC friendly)
|
|
58
|
-
lastArgs = null;
|
|
59
|
-
lastThis = null;
|
|
60
|
-
|
|
61
|
-
abort.remove();
|
|
62
|
-
fn.apply(ctx, args);
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
const cancel = () => {
|
|
66
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
67
|
-
timeoutId = 0;
|
|
68
|
-
|
|
69
|
-
lastArgs = null;
|
|
70
|
-
lastThis = null;
|
|
71
|
-
|
|
72
|
-
abort.remove();
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
/** @type {any} */
|
|
76
|
-
const debounced = function (...args) {
|
|
77
|
-
if (signal?.aborted) return;
|
|
78
|
-
|
|
79
|
-
lastArgs = args;
|
|
80
|
-
lastThis = this;
|
|
81
|
-
|
|
82
|
-
if (timeoutId) clearTimeout(timeoutId);
|
|
83
|
-
|
|
84
|
-
// Listener should exist only while a call is pending
|
|
85
|
-
abort.add();
|
|
86
|
-
|
|
87
|
-
timeoutId = setTimeout(() => {
|
|
88
|
-
timeoutId = 0;
|
|
89
|
-
invoke();
|
|
90
|
-
}, wait);
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
debounced.cancel = cancel;
|
|
94
|
-
|
|
95
|
-
debounced.flush = () => {
|
|
96
|
-
if (!timeoutId) return;
|
|
97
|
-
clearTimeout(timeoutId);
|
|
98
|
-
timeoutId = 0;
|
|
99
|
-
invoke();
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
// If already aborted at creation time, ensure clean slate.
|
|
103
|
-
if (signal?.aborted) cancel();
|
|
104
|
-
|
|
105
|
-
return debounced;
|
|
1
|
+
// ./src/debounce.js
|
|
2
|
+
|
|
3
|
+
import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
|
|
4
|
+
import { pendingAbort } from './abort.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {((...args: any[]) => void) & {
|
|
8
|
+
* cancel: () => void,
|
|
9
|
+
* flush: () => void
|
|
10
|
+
* }} DebouncedFunction
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Creates a debounced function that delays invoking `fn`
|
|
15
|
+
* until after `delay` ms of inactivity.
|
|
16
|
+
*
|
|
17
|
+
* Preferred:
|
|
18
|
+
* - debounce(fn, [delay], [options]) // delay defaults to 0
|
|
19
|
+
*
|
|
20
|
+
* Also supported:
|
|
21
|
+
* - debounce(delay, fn, [options]) // legacy/alt ordering
|
|
22
|
+
* - debounce(fn, [options])
|
|
23
|
+
*
|
|
24
|
+
* Notes:
|
|
25
|
+
* - Always invokes with the latest arguments/context.
|
|
26
|
+
* - `.cancel()` clears any pending invocation.
|
|
27
|
+
* - `.flush()` immediately invokes if pending.
|
|
28
|
+
* - Optional AbortSignal: abort cancels pending invocation.
|
|
29
|
+
*
|
|
30
|
+
* @param {Function|string|number} a - Function or delay (see overloads)
|
|
31
|
+
* @param {Function|string|number|Object} [b] - Delay, function, or options
|
|
32
|
+
* @param {Object} [c] - Options (3-arg form)
|
|
33
|
+
* @param {AbortSignal} [c.signal] - Optional AbortSignal to cancel pending work
|
|
34
|
+
* @returns {DebouncedFunction}
|
|
35
|
+
*/
|
|
36
|
+
export function debounce(a, b, c) {
|
|
37
|
+
const { fn, delay, options } = resolveDelayFnOptions(a, b, c, 0);
|
|
38
|
+
const signal = options?.signal;
|
|
39
|
+
|
|
40
|
+
const wait = Math.max(0, delay);
|
|
41
|
+
|
|
42
|
+
let timeoutId = 0;
|
|
43
|
+
|
|
44
|
+
/** @type {any[] | null} */
|
|
45
|
+
let lastArgs = null;
|
|
46
|
+
/** @type {any | null} */
|
|
47
|
+
let lastThis = null;
|
|
48
|
+
|
|
49
|
+
const abort = pendingAbort(signal, () => cancel());
|
|
50
|
+
|
|
51
|
+
const invoke = () => {
|
|
52
|
+
if (!lastArgs) return;
|
|
53
|
+
|
|
54
|
+
const args = lastArgs;
|
|
55
|
+
const ctx = lastThis;
|
|
56
|
+
|
|
57
|
+
// clear first (re-entrancy safe + GC friendly)
|
|
58
|
+
lastArgs = null;
|
|
59
|
+
lastThis = null;
|
|
60
|
+
|
|
61
|
+
abort.remove();
|
|
62
|
+
fn.apply(ctx, args);
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const cancel = () => {
|
|
66
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
67
|
+
timeoutId = 0;
|
|
68
|
+
|
|
69
|
+
lastArgs = null;
|
|
70
|
+
lastThis = null;
|
|
71
|
+
|
|
72
|
+
abort.remove();
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** @type {any} */
|
|
76
|
+
const debounced = function (...args) {
|
|
77
|
+
if (signal?.aborted) return;
|
|
78
|
+
|
|
79
|
+
lastArgs = args;
|
|
80
|
+
lastThis = this;
|
|
81
|
+
|
|
82
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
83
|
+
|
|
84
|
+
// Listener should exist only while a call is pending
|
|
85
|
+
abort.add();
|
|
86
|
+
|
|
87
|
+
timeoutId = setTimeout(() => {
|
|
88
|
+
timeoutId = 0;
|
|
89
|
+
invoke();
|
|
90
|
+
}, wait);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
debounced.cancel = cancel;
|
|
94
|
+
|
|
95
|
+
debounced.flush = () => {
|
|
96
|
+
if (!timeoutId) return;
|
|
97
|
+
clearTimeout(timeoutId);
|
|
98
|
+
timeoutId = 0;
|
|
99
|
+
invoke();
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// If already aborted at creation time, ensure clean slate.
|
|
103
|
+
if (signal?.aborted) cancel();
|
|
104
|
+
|
|
105
|
+
return debounced;
|
|
106
106
|
}
|
package/src/every.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
// ./src/every.js
|
|
2
|
-
import { EveryTimer } from './EveryTimer.js';
|
|
3
|
-
import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Runs a function every N ms with optional execution limit.
|
|
7
|
-
*
|
|
8
|
-
* Preferred:
|
|
9
|
-
* - every(fn, duration, [options])
|
|
10
|
-
*
|
|
11
|
-
* Also supported (legacy/alt):
|
|
12
|
-
* - every(duration, fn, [options])
|
|
13
|
-
*
|
|
14
|
-
* @param {Function|string|number} a - Function or duration (see overloads)
|
|
15
|
-
* @param {Function|string|number|Object} b - Duration, function, or options
|
|
16
|
-
* @param {Object} [c] - Options
|
|
17
|
-
* @param {number} [c.max=Infinity] - Max times to run
|
|
18
|
-
* @param {boolean} [c.runImmediately=false] - Run immediately on first tick
|
|
19
|
-
* @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
|
|
20
|
-
* @returns {{
|
|
21
|
-
* pause(): void,
|
|
22
|
-
* resume(): void,
|
|
23
|
-
* cancel(): void,
|
|
24
|
-
* reset(restart?: boolean): void,
|
|
25
|
-
* readonly isRunning: boolean,
|
|
26
|
-
* readonly isPaused: boolean,
|
|
27
|
-
* readonly isFinished: boolean,
|
|
28
|
-
* readonly count: number
|
|
29
|
-
* }}
|
|
30
|
-
*/
|
|
31
|
-
export function every(a, b, c) {
|
|
32
|
-
// require explicit duration: defaultDelay = undefined
|
|
33
|
-
const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
|
|
34
|
-
return new EveryTimer(delay, fn, options);
|
|
1
|
+
// ./src/every.js
|
|
2
|
+
import { EveryTimer } from './EveryTimer.js';
|
|
3
|
+
import { resolveDelayFnOptions } from './resolveDelayAndFn.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Runs a function every N ms with optional execution limit.
|
|
7
|
+
*
|
|
8
|
+
* Preferred:
|
|
9
|
+
* - every(fn, duration, [options])
|
|
10
|
+
*
|
|
11
|
+
* Also supported (legacy/alt):
|
|
12
|
+
* - every(duration, fn, [options])
|
|
13
|
+
*
|
|
14
|
+
* @param {Function|string|number} a - Function or duration (see overloads)
|
|
15
|
+
* @param {Function|string|number|Object} b - Duration, function, or options
|
|
16
|
+
* @param {Object} [c] - Options
|
|
17
|
+
* @param {number} [c.max=Infinity] - Max times to run
|
|
18
|
+
* @param {boolean} [c.runImmediately=false] - Run immediately on first tick
|
|
19
|
+
* @param {AbortSignal} [c.signal] - Optional AbortSignal to auto-cancel
|
|
20
|
+
* @returns {{
|
|
21
|
+
* pause(): void,
|
|
22
|
+
* resume(): void,
|
|
23
|
+
* cancel(): void,
|
|
24
|
+
* reset(restart?: boolean): void,
|
|
25
|
+
* readonly isRunning: boolean,
|
|
26
|
+
* readonly isPaused: boolean,
|
|
27
|
+
* readonly isFinished: boolean,
|
|
28
|
+
* readonly count: number
|
|
29
|
+
* }}
|
|
30
|
+
*/
|
|
31
|
+
export function every(a, b, c) {
|
|
32
|
+
// require explicit duration: defaultDelay = undefined
|
|
33
|
+
const { fn, delay, options } = resolveDelayFnOptions(a, b, c, undefined);
|
|
34
|
+
return new EveryTimer(delay, fn, options);
|
|
35
35
|
}
|
package/src/index.js
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
|
-
// ./src/index.js
|
|
2
|
-
|
|
3
|
-
export { parseDuration } from './parseDuration.js';
|
|
4
|
-
|
|
5
|
-
export { flow } from './TimeoutFlow.js';
|
|
6
|
-
|
|
7
|
-
export { throttle } from './throttle.js';
|
|
8
|
-
export { debounce } from './debounce.js';
|
|
9
|
-
|
|
10
|
-
export { after } from './after.js';
|
|
11
|
-
export { every } from './every.js';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
export {
|
|
15
|
-
export {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
1
|
+
// ./src/index.js
|
|
2
|
+
|
|
3
|
+
export { parseDuration } from './parseDuration.js';
|
|
4
|
+
|
|
5
|
+
export { flow } from './TimeoutFlow.js';
|
|
6
|
+
|
|
7
|
+
export { throttle } from './throttle.js';
|
|
8
|
+
export { debounce } from './debounce.js';
|
|
9
|
+
|
|
10
|
+
export { after } from './after.js';
|
|
11
|
+
export { every } from './every.js';
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
export { sleep } from './sleep.js';
|
|
15
|
+
export { waitFor } from './waitFor.js';
|
|
16
|
+
export { retry } from './retry.js';
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
export {
|
|
20
|
+
afterRaf,
|
|
21
|
+
everyRaf,
|
|
22
|
+
debounceRaf,
|
|
23
|
+
throttleRaf,
|
|
24
|
+
waitForRaf
|
|
24
25
|
} from './raf/index.js';
|
package/src/now.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
// ./src/now.js
|
|
2
|
-
|
|
3
|
-
// We resolve the best available clock implementation *once* at module load time.
|
|
4
|
-
// This avoids doing feature detection on every call to `now()`,
|
|
5
|
-
// keeping the hot path branch-free and fast.
|
|
6
|
-
|
|
7
|
-
let now;
|
|
8
|
-
|
|
9
|
-
// Prefer high-resolution, monotonic clock when available.
|
|
10
|
-
// - Browsers: performance.now()
|
|
11
|
-
// - Modern Node: performance.now()
|
|
12
|
-
// This is ideal for measuring elapsed time.
|
|
13
|
-
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
|
|
14
|
-
now = () => performance.now();
|
|
15
|
-
} else {
|
|
16
|
-
// Fallback for older Node or minimal runtimes.
|
|
17
|
-
// Date.now() is not monotonic, but ensures compatibility.
|
|
18
|
-
now = () => Date.now();
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// Export the resolved implementation.
|
|
22
|
-
// Consumers simply call `now()` without worrying about environment differences.
|
|
1
|
+
// ./src/now.js
|
|
2
|
+
|
|
3
|
+
// We resolve the best available clock implementation *once* at module load time.
|
|
4
|
+
// This avoids doing feature detection on every call to `now()`,
|
|
5
|
+
// keeping the hot path branch-free and fast.
|
|
6
|
+
|
|
7
|
+
let now;
|
|
8
|
+
|
|
9
|
+
// Prefer high-resolution, monotonic clock when available.
|
|
10
|
+
// - Browsers: performance.now()
|
|
11
|
+
// - Modern Node: performance.now()
|
|
12
|
+
// This is ideal for measuring elapsed time.
|
|
13
|
+
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
|
|
14
|
+
now = () => performance.now();
|
|
15
|
+
} else {
|
|
16
|
+
// Fallback for older Node or minimal runtimes.
|
|
17
|
+
// Date.now() is not monotonic, but ensures compatibility.
|
|
18
|
+
now = () => Date.now();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Export the resolved implementation.
|
|
22
|
+
// Consumers simply call `now()` without worrying about environment differences.
|
|
23
23
|
export { now };
|
package/src/parseDuration.js
CHANGED
|
@@ -1,47 +1,44 @@
|
|
|
1
|
-
// ./src/parseDuration.js
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Parses a duration string like "2s", "1.5m", "500ms" into milliseconds.
|
|
6
|
-
* Also accepts raw number values (treated as ms).
|
|
7
|
-
* @param {string|number} input
|
|
8
|
-
* @returns {number}
|
|
9
|
-
*/
|
|
10
|
-
export function parseDuration(input) {
|
|
11
|
-
if (typeof input === 'number') {
|
|
12
|
-
if (!Number.isFinite(input)) {
|
|
13
|
-
throw new TypeError(`Expected a finite number of ms, got: ${input}`);
|
|
14
|
-
}
|
|
15
|
-
return input;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
if (typeof input !== 'string') {
|
|
19
|
-
throw new TypeError(`Expected a duration string or number, got ${typeof input}`);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const str = input.toLowerCase().trim();
|
|
23
|
-
const match = str.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
|
|
24
|
-
|
|
25
|
-
if (!match) {
|
|
26
|
-
throw new Error(
|
|
27
|
-
`Invalid duration format: "${input}". Expected formats like "500ms", "2s", "1.5m", or "1h".`
|
|
28
|
-
);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const value = Number(match[1]);
|
|
32
|
-
if (!Number.isFinite(value)) {
|
|
33
|
-
throw new TypeError(`Invalid duration value: "${match[1]}"`);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
const unit = match[2];
|
|
37
|
-
|
|
38
|
-
switch (unit) {
|
|
39
|
-
case 'ms': return value;
|
|
40
|
-
case 's': return value * 1000;
|
|
41
|
-
case 'm': return value * 60_000;
|
|
42
|
-
case 'h': return value * 3_600_000;
|
|
43
|
-
|
|
44
|
-
// Should be unreachable due to regex, but keeps function total.
|
|
45
|
-
throw new Error(`Unsupported duration unit: "${unit}"`);
|
|
46
|
-
}
|
|
1
|
+
// ./src/parseDuration.js
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Parses a duration string like "2s", "1.5m", "500ms" into milliseconds.
|
|
6
|
+
* Also accepts raw number values (treated as ms).
|
|
7
|
+
* @param {string|number} input
|
|
8
|
+
* @returns {number}
|
|
9
|
+
*/
|
|
10
|
+
export function parseDuration(input) {
|
|
11
|
+
if (typeof input === 'number') {
|
|
12
|
+
if (!Number.isFinite(input)) {
|
|
13
|
+
throw new TypeError(`Expected a finite number of ms, got: ${input}`);
|
|
14
|
+
}
|
|
15
|
+
return input;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (typeof input !== 'string') {
|
|
19
|
+
throw new TypeError(`Expected a duration string or number, got ${typeof input}`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const str = input.toLowerCase().trim();
|
|
23
|
+
const match = str.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
|
|
24
|
+
|
|
25
|
+
if (!match) {
|
|
26
|
+
throw new Error(
|
|
27
|
+
`Invalid duration format: "${input}". Expected formats like "500ms", "2s", "1.5m", or "1h".`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const value = Number(match[1]);
|
|
32
|
+
if (!Number.isFinite(value)) {
|
|
33
|
+
throw new TypeError(`Invalid duration value: "${match[1]}"`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const unit = match[2];
|
|
37
|
+
|
|
38
|
+
switch (unit) {
|
|
39
|
+
case 'ms': return value;
|
|
40
|
+
case 's': return value * 1000;
|
|
41
|
+
case 'm': return value * 60_000;
|
|
42
|
+
case 'h': return value * 3_600_000;
|
|
43
|
+
}
|
|
47
44
|
}
|
package/src/raf/ReadMe-Raf.md
CHANGED
|
@@ -1,94 +1,94 @@
|
|
|
1
|
-
## Frame-Based Timing (RAF Utilities)
|
|
2
|
-
|
|
3
|
-
These helpers use `requestAnimationFrame` under the hood to provide smooth, energy-efficient timing. Ideal for visual UI flows, canvas apps, scroll/resize behavior, and performance-sensitive interactions.
|
|
4
|
-
|
|
5
|
-
All `raf` utilities automatically **pause in background tabs**, unlike timers.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
### 👉 API Summary
|
|
10
|
-
|
|
11
|
-
| Function | Purpose | Best For |
|
|
12
|
-
|-------------------------|-------------------------------------------------------------------------|------------------------------------------------|
|
|
13
|
-
| `afterRaf()` | Runs a function **once after N ms**, using `requestAnimationFrame`. | Idle effects, UI post-load, paint batching |
|
|
14
|
-
| `everyRaf()` | Repeats a function **every N ms**, throttled via frames. | Sanity loops, smooth polling, visual checks |
|
|
15
|
-
| `debounceRaf()` | Debounces a function using **frames instead of timeouts**. | Drag/move handlers, visual updates |
|
|
16
|
-
| `debounceRaf('300ms', fn)` | Debounces like traditional debounce, but frame-aware. | Resize events, paused background flows |
|
|
17
|
-
| `throttleRaf()` | Throttles execution to **at most once per frame**. | Scroll events, pointermove, paint-heavy flows |
|
|
18
|
-
| `throttleRaf(fn, 2)` | Throttles to once every 3 frames (`frameSkip = 2`). | Advanced visuals, slower sync without timers |
|
|
19
|
-
| `waitForRaf()` | Waits for a condition to become true using a frame-based loop. | DOM readiness, layout stability, visibility checks |
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
### ✨ Key Advantages
|
|
24
|
-
|
|
25
|
-
- 🔄 **Frame-sync**: Triggered in sync with visual updates (60Hz or higher)
|
|
26
|
-
- 🛌 **Background-tab safe**: No CPU use when inactive
|
|
27
|
-
- ⚡ **Energy efficient**: Great for battery-conscious apps
|
|
28
|
-
- 🧘 **Smoother UX**: Especially under load or heavy visuals
|
|
29
|
-
|
|
30
|
-
---
|
|
31
|
-
|
|
32
|
-
### 🛠 Example Usage
|
|
33
|
-
|
|
34
|
-
```js
|
|
35
|
-
import { debounceRaf } from './raf/debounceRaf.js';
|
|
36
|
-
|
|
37
|
-
// Wait 1 frame after rapid calls
|
|
38
|
-
const onMouseMove = debounceRaf(() => {
|
|
39
|
-
drawPreview();
|
|
40
|
-
});
|
|
41
|
-
|
|
42
|
-
// Wait 250ms of inactivity (with frame-based throttle)
|
|
43
|
-
const onResize = debounceRaf('250ms', () => {
|
|
44
|
-
updateLayout();
|
|
45
|
-
});
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
```js
|
|
49
|
-
import { afterRaf } from './raf/afterRaf.js';
|
|
50
|
-
|
|
51
|
-
afterRaf('2s', () => {
|
|
52
|
-
showIntroAnimation();
|
|
53
|
-
});
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
```js
|
|
57
|
-
import { everyRaf } from './raf/everyRaf.js';
|
|
58
|
-
|
|
59
|
-
const loop = everyRaf('1s', () => {
|
|
60
|
-
console.log('heartbeat');
|
|
61
|
-
});
|
|
62
|
-
```
|
|
63
|
-
|
|
64
|
-
```js
|
|
65
|
-
import { throttleRaf } from './raf/throttleRaf.js';
|
|
66
|
-
|
|
67
|
-
// Throttle a scroll event to at most once per animation frame
|
|
68
|
-
const onScroll = throttleRaf((e) => {
|
|
69
|
-
handleScroll(e);
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
// Throttle to once every 3 frames (skip 2 frames)
|
|
73
|
-
const onDrag = throttleRaf(drawFrame, 2);
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
```js
|
|
77
|
-
import { waitForRaf } from './raf/waitForRaf.js';
|
|
78
|
-
|
|
79
|
-
// Wait for an element to become visible or stable
|
|
80
|
-
await waitForRaf(() => document.querySelector('#panel')?.offsetHeight > 0);
|
|
81
|
-
```
|
|
82
|
-
|
|
83
|
-
---
|
|
84
|
-
|
|
85
|
-
### 📦 File Locations
|
|
86
|
-
|
|
87
|
-
| File | Description |
|
|
88
|
-
|-----------------------|---------------------------------------------------------|
|
|
89
|
-
| `raf/afterRaf.js` | One-time timer with frame pause support |
|
|
90
|
-
| `raf/everyRaf.js` | Interval timer using `requestAnimationFrame` |
|
|
91
|
-
| `raf/debounceRaf.js` | Smart debounce with optional duration and frame pause |
|
|
92
|
-
| `raf/throttleRaf.js` | Input-event throttle using frame-skip control |
|
|
93
|
-
| `raf/waitForRaf.js` | Waits for truthy condition using passive frame polling |
|
|
94
|
-
|
|
1
|
+
## Frame-Based Timing (RAF Utilities)
|
|
2
|
+
|
|
3
|
+
These helpers use `requestAnimationFrame` under the hood to provide smooth, energy-efficient timing. Ideal for visual UI flows, canvas apps, scroll/resize behavior, and performance-sensitive interactions.
|
|
4
|
+
|
|
5
|
+
All `raf` utilities automatically **pause in background tabs**, unlike timers.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
### 👉 API Summary
|
|
10
|
+
|
|
11
|
+
| Function | Purpose | Best For |
|
|
12
|
+
|-------------------------|-------------------------------------------------------------------------|------------------------------------------------|
|
|
13
|
+
| `afterRaf()` | Runs a function **once after N ms**, using `requestAnimationFrame`. | Idle effects, UI post-load, paint batching |
|
|
14
|
+
| `everyRaf()` | Repeats a function **every N ms**, throttled via frames. | Sanity loops, smooth polling, visual checks |
|
|
15
|
+
| `debounceRaf()` | Debounces a function using **frames instead of timeouts**. | Drag/move handlers, visual updates |
|
|
16
|
+
| `debounceRaf('300ms', fn)` | Debounces like traditional debounce, but frame-aware. | Resize events, paused background flows |
|
|
17
|
+
| `throttleRaf()` | Throttles execution to **at most once per frame**. | Scroll events, pointermove, paint-heavy flows |
|
|
18
|
+
| `throttleRaf(fn, 2)` | Throttles to once every 3 frames (`frameSkip = 2`). | Advanced visuals, slower sync without timers |
|
|
19
|
+
| `waitForRaf()` | Waits for a condition to become true using a frame-based loop. | DOM readiness, layout stability, visibility checks |
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
### ✨ Key Advantages
|
|
24
|
+
|
|
25
|
+
- 🔄 **Frame-sync**: Triggered in sync with visual updates (60Hz or higher)
|
|
26
|
+
- 🛌 **Background-tab safe**: No CPU use when inactive
|
|
27
|
+
- ⚡ **Energy efficient**: Great for battery-conscious apps
|
|
28
|
+
- 🧘 **Smoother UX**: Especially under load or heavy visuals
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
### 🛠 Example Usage
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { debounceRaf } from './raf/debounceRaf.js';
|
|
36
|
+
|
|
37
|
+
// Wait 1 frame after rapid calls
|
|
38
|
+
const onMouseMove = debounceRaf(() => {
|
|
39
|
+
drawPreview();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Wait 250ms of inactivity (with frame-based throttle)
|
|
43
|
+
const onResize = debounceRaf('250ms', () => {
|
|
44
|
+
updateLayout();
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { afterRaf } from './raf/afterRaf.js';
|
|
50
|
+
|
|
51
|
+
afterRaf('2s', () => {
|
|
52
|
+
showIntroAnimation();
|
|
53
|
+
});
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
import { everyRaf } from './raf/everyRaf.js';
|
|
58
|
+
|
|
59
|
+
const loop = everyRaf('1s', () => {
|
|
60
|
+
console.log('heartbeat');
|
|
61
|
+
});
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
import { throttleRaf } from './raf/throttleRaf.js';
|
|
66
|
+
|
|
67
|
+
// Throttle a scroll event to at most once per animation frame
|
|
68
|
+
const onScroll = throttleRaf((e) => {
|
|
69
|
+
handleScroll(e);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Throttle to once every 3 frames (skip 2 frames)
|
|
73
|
+
const onDrag = throttleRaf(drawFrame, 2);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
```js
|
|
77
|
+
import { waitForRaf } from './raf/waitForRaf.js';
|
|
78
|
+
|
|
79
|
+
// Wait for an element to become visible or stable
|
|
80
|
+
await waitForRaf(() => document.querySelector('#panel')?.offsetHeight > 0);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
### 📦 File Locations
|
|
86
|
+
|
|
87
|
+
| File | Description |
|
|
88
|
+
|-----------------------|---------------------------------------------------------|
|
|
89
|
+
| `raf/afterRaf.js` | One-time timer with frame pause support |
|
|
90
|
+
| `raf/everyRaf.js` | Interval timer using `requestAnimationFrame` |
|
|
91
|
+
| `raf/debounceRaf.js` | Smart debounce with optional duration and frame pause |
|
|
92
|
+
| `raf/throttleRaf.js` | Input-event throttle using frame-skip control |
|
|
93
|
+
| `raf/waitForRaf.js` | Waits for truthy condition using passive frame polling |
|
|
94
|
+
|