timeout-flow 0.0.1

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.
@@ -0,0 +1,38 @@
1
+
2
+ // ./raf/throttleRaf.js
3
+
4
+ /**
5
+ * Throttles a function using requestAnimationFrame with optional frame skipping.
6
+ * Ensures the function runs at most once per N-frames.
7
+ * - frameSkip = 0 → run every frame
8
+ * - frameSkip = 1 → run every 2nd frame
9
+ * - frameSkip = 2 → run every 3rd frame, etc.
10
+ *
11
+ * @param {Function} fn - Function to throttle
12
+ * @param {number} [frameSkip=0] - Number of frames to skip between calls
13
+ * @returns {Function} throttled function
14
+ */
15
+ export function throttleRaf(fn, frameSkip = 0) {
16
+ let scheduled = false;
17
+ let lastArgs = null;
18
+ let frameCount = 0;
19
+
20
+ return (...args) => {
21
+ lastArgs = args;
22
+
23
+ if (!scheduled) {
24
+ scheduled = true;
25
+ requestAnimationFrame(function tick() {
26
+ if (frameCount >= frameSkip) {
27
+ fn(...lastArgs);
28
+ frameCount = 0;
29
+ scheduled = false;
30
+ } else {
31
+ frameCount++;
32
+ requestAnimationFrame(tick);
33
+ }
34
+ });
35
+ }
36
+ };
37
+ }
38
+
@@ -0,0 +1,33 @@
1
+ // ./raf/waitForRaf.js
2
+ import { parseDuration } from '../src/parseDuration.js';
3
+
4
+ /**
5
+ * Waits for a condition to return truthy, polling each frame.
6
+ * - Ideal for visual state: DOM settling, visibility, layout changes.
7
+ * - Respects tab inactivity (pause-safe).
8
+ *
9
+ * @param {Function} condition - Function returning truthy when complete
10
+ * @param {Object} [options]
11
+ * @param {string|number} [options.timeout] - Optional max time to wait
12
+ * @returns {Promise<void>} Resolves when condition is met, rejects on timeout
13
+ */
14
+ export function waitForRaf(condition, { timeout } = {}) {
15
+ return new Promise((resolve, reject) => {
16
+ const start = performance.now();
17
+ const timeoutMs = timeout ? parseDuration(timeout) : null;
18
+
19
+ const tick = (timestamp) => {
20
+ if (condition()) {
21
+ return resolve();
22
+ }
23
+
24
+ if (timeoutMs && timestamp - start >= timeoutMs) {
25
+ return reject(new Error('waitForRaf timed out'));
26
+ }
27
+
28
+ requestAnimationFrame(tick);
29
+ };
30
+
31
+ requestAnimationFrame(tick);
32
+ });
33
+ }
@@ -0,0 +1,21 @@
1
+ // ./src/AfterTimer.js
2
+ import { TimerBase } from './TimerBase.js';
3
+
4
+ /**
5
+ * Executes a function once after a delay.
6
+ */
7
+ export class AfterTimer extends TimerBase {
8
+ /**
9
+ * @param {string|number} duration - Delay before firing (e.g., '1s', 300)
10
+ * @param {Function} fn - Main function to execute
11
+ * @param {Function} [onFinish] - Optional callback when done
12
+ */
13
+ constructor(duration, fn, onFinish) {
14
+ super(duration);
15
+ this.resume(() => {
16
+ fn?.();
17
+ onFinish?.();
18
+ });
19
+ }
20
+ }
21
+
@@ -0,0 +1,88 @@
1
+ // ./src/EveryTimer.js
2
+ import { TimerBase } from './TimerBase.js';
3
+ import { parseDuration } from './parseDuration.js';
4
+
5
+ /**
6
+ * Repeatedly runs a function every N ms, with optional max count.
7
+ */
8
+ export class EveryTimer {
9
+ #interval;
10
+ #fn;
11
+ #max;
12
+ #count = 0;
13
+ #running = false;
14
+ #controller = null;
15
+
16
+ /**
17
+ * @param {string|number} duration - Delay between calls (e.g., '1s', 200)
18
+ * @param {Function} fn - Function to call each tick
19
+ * @param {number} [max=Infinity] - Max executions
20
+ * @param {boolean} [runImmediately=false] - Run `fn` once before first delay
21
+ */
22
+ constructor(duration, fn, max = Infinity, runImmediately = false) {
23
+ this.#interval = parseDuration(duration);
24
+ this.#fn = fn;
25
+ this.#max = max;
26
+
27
+ if (runImmediately) {
28
+ this.#tick();
29
+ } else {
30
+ this.#schedule();
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Number of times `fn` has been executed.
36
+ */
37
+ get count() {
38
+ return this.#count;
39
+ }
40
+
41
+ /**
42
+ * Whether the timer is actively running.
43
+ */
44
+ get isRunning() {
45
+ return this.#running;
46
+ }
47
+
48
+ #tick = () => {
49
+ if (this.#count >= this.#max) {
50
+ this.cancel();
51
+ return;
52
+ }
53
+
54
+ this.#fn?.(this.#count++);
55
+ this.#schedule();
56
+ };
57
+
58
+ #schedule() {
59
+ this.#controller = new TimerBase(this.#interval);
60
+ this.#running = true;
61
+ this.#controller.resume(this.#tick);
62
+ }
63
+
64
+ pause() {
65
+ this.#controller?.pause();
66
+ this.#running = false;
67
+ }
68
+
69
+ resume() {
70
+ if (!this.#running && this.#count < this.#max) {
71
+ this.#controller?.resume(this.#tick);
72
+ this.#running = true;
73
+ }
74
+ }
75
+
76
+ cancel() {
77
+ this.#controller?.cancel();
78
+ this.#running = false;
79
+ }
80
+
81
+ reset(restart = false) {
82
+ this.cancel();
83
+ this.#count = 0;
84
+ if (restart) this.#schedule();
85
+ }
86
+ }
87
+
88
+
@@ -0,0 +1,228 @@
1
+
2
+ // ./src/TimeoutFlow.js
3
+
4
+ import { after } from './after.js';
5
+ import { every } from './every.js';
6
+
7
+ /**
8
+ * Creates a fluent scheduler.
9
+ * Returns a chainable timeline.
10
+ */
11
+ export function flow() {
12
+ const steps = [];
13
+ let currentIndex = 0;
14
+ let isPaused = false;
15
+ let isCancelled = false;
16
+ let loopEnabled = false;
17
+ let loopLimit = Infinity;
18
+ let loopCount = 0;
19
+ let onFinishCallback = null;
20
+ const labelMap = new Map();
21
+ let jumpTarget = null;
22
+ let conditionStack = [];
23
+ let skipMode = false;
24
+ let whileCondition = null;
25
+ let doWhileCondition = null;
26
+
27
+ const runner = {
28
+
29
+ after(duration, fn) {
30
+ steps.push({ type: 'after', duration, fn });
31
+ return runner;
32
+ },
33
+
34
+ every(duration, fn, times = Infinity) {
35
+ steps.push({
36
+ type: 'every',
37
+ duration,
38
+ fn,
39
+ times,
40
+ whileCondition,
41
+ doWhileCondition
42
+ });
43
+ whileCondition = null;
44
+ doWhileCondition = null;
45
+ return runner;
46
+ },
47
+
48
+ loop(n = true) {
49
+ loopEnabled = true;
50
+ loopLimit = n === true ? Infinity : n;
51
+ return runner;
52
+ },
53
+
54
+ onFinish(cb) {
55
+ onFinishCallback = cb;
56
+ return runner;
57
+ },
58
+
59
+ start() {
60
+ isCancelled = false;
61
+ isPaused = false;
62
+ currentIndex = 0;
63
+ loopCount = 0;
64
+ executeNext();
65
+ return runner;
66
+ },
67
+
68
+ pause() {
69
+ if (isPaused || isCancelled) return;
70
+ isPaused = true;
71
+ steps[currentIndex]?.controller?.pause?.();
72
+ },
73
+
74
+ resume() {
75
+ if (!isPaused || isCancelled) return;
76
+ isPaused = false;
77
+ steps[currentIndex]?.controller?.resume?.();
78
+ },
79
+
80
+ cancel() {
81
+ isCancelled = true;
82
+ const step = steps[currentIndex];
83
+ step?.controller?.cancel?.();
84
+ step.controller = null;
85
+ },
86
+
87
+ reset() {
88
+ runner.cancel();
89
+ steps.length = 0;
90
+ currentIndex = 0;
91
+ loopCount = 0;
92
+ onFinishCallback = null;
93
+ return runner;
94
+ },
95
+
96
+ get isPaused() {
97
+ return isPaused;
98
+ },
99
+
100
+ label(name) {
101
+ labelMap.set(name, steps.length); // point to next step index
102
+ return runner;
103
+ },
104
+
105
+ jumpTo(name) {
106
+ jumpTarget = name;
107
+ return runner;
108
+ },
109
+
110
+ if(predicate) {
111
+ conditionStack.push(() => (typeof predicate === 'function' ? predicate() : !!predicate));
112
+ return runner;
113
+ },
114
+
115
+ unless(predicate) {
116
+ conditionStack.push(() => !(typeof predicate === 'function' ? predicate() : !!predicate));
117
+ return runner;
118
+ },
119
+
120
+ while(predicate) {
121
+ whileCondition = () => (typeof predicate === 'function' ? predicate() : !!predicate);
122
+ return runner;
123
+ },
124
+
125
+ doWhile(predicate) {
126
+ doWhileCondition = () => (typeof predicate === 'function' ? predicate() : !!predicate);
127
+ return runner;
128
+ }
129
+
130
+ };
131
+
132
+ function increment_step(step = null) {
133
+ if (step?.controller) step.controller = null;
134
+ currentIndex++;
135
+ executeNext();
136
+ }
137
+
138
+ function executeNext() {
139
+ if (isCancelled || isPaused) return;
140
+
141
+ if (jumpTarget) {
142
+ const targetIndex = labelMap.get(jumpTarget);
143
+ if (typeof targetIndex === 'number') {
144
+ currentIndex = targetIndex;
145
+ } else {
146
+ throw new Error(`Label "${jumpTarget}" not found`);
147
+ }
148
+ jumpTarget = null; // reset after jump
149
+ }
150
+
151
+ // Handle if conditions
152
+ if (conditionStack.length > 0) {
153
+ const shouldRun = conditionStack.shift()(); // run & remove
154
+ if (!shouldRun) {
155
+ skipMode = true;
156
+ }
157
+ }
158
+
159
+ // Skip logic
160
+ if (skipMode) {
161
+ const next = steps[currentIndex];
162
+ if (!next || next.type === 'label') {
163
+ skipMode = false; // stop skipping at label
164
+ } else {
165
+ return increment_step(step);
166
+ }
167
+ }
168
+
169
+ // End of timeline
170
+ const step = steps[currentIndex];
171
+
172
+ if (!step || currentIndex >= steps.length) {
173
+ if (loopEnabled && ++loopCount < loopLimit) {
174
+ currentIndex = 0;
175
+ executeNext();
176
+ } else {
177
+ onFinishCallback?.();
178
+ }
179
+ return;
180
+ }
181
+
182
+
183
+ if (step.type === 'after') {
184
+ step.controller = after(step.duration, step.fn, () => increment_step(step));
185
+ return
186
+ }
187
+
188
+ if (step.type === 'every') {
189
+ let count = 0;
190
+ let firstRun = true;
191
+
192
+ const ctrl = every(step.duration, () => {
193
+ if (isPaused || isCancelled) return;
194
+
195
+ // Handle .while (skip when fails before run)
196
+ if (step.whileCondition && !step.whileCondition()) {
197
+ ctrl.cancel();
198
+ return increment_step(step);
199
+ }
200
+
201
+ // Run fn first
202
+ step.fn(count++);
203
+ firstRun = false;
204
+
205
+ // Check doWhile after first execution
206
+ if (!firstRun && step.doWhileCondition && !step.doWhileCondition()) {
207
+ ctrl.cancel();
208
+ return increment_step(step);
209
+ }
210
+
211
+ if (count >= step.times) {
212
+ ctrl.cancel();
213
+ return increment_step(step);
214
+ }
215
+ }, step.times);
216
+
217
+ step.controller = ctrl;
218
+ }
219
+
220
+ if (step.type === 'label') {
221
+ return increment_step(step);
222
+ }
223
+
224
+
225
+ }
226
+
227
+ return runner;
228
+ }
@@ -0,0 +1,98 @@
1
+ // ./src/TimerBase.js
2
+ import { parseDuration } from './parseDuration.js';
3
+
4
+ /**
5
+ * Base timer class to manage pause/resume/cancel behavior.
6
+ * Not meant to be used directly—subclass for concrete behavior.
7
+ */
8
+ export class TimerBase {
9
+ #ms;
10
+ #startTime = null;
11
+ #remaining;
12
+ #timer = null;
13
+ #running = false;
14
+
15
+ /**
16
+ * @param {string|number} duration - The duration to wait in ms or shorthand format
17
+ */
18
+ constructor(duration) {
19
+ this.#ms = parseDuration(duration);
20
+ this.#remaining = this.#ms;
21
+ }
22
+
23
+ /**
24
+ * Whether the timer is currently running.
25
+ * @returns {boolean}
26
+ */
27
+ get isRunning() {
28
+ return this.#running;
29
+ }
30
+
31
+ /**
32
+ * Pause the active timer, storing remaining time.
33
+ */
34
+ pause() {
35
+ if (this.#running) {
36
+ clearTimeout(this.#timer);
37
+ this.#remaining -= Date.now() - this.#startTime;
38
+ this.#running = false;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Resume the timer using the remaining time.
44
+ * @param {Function} callback - Called when time completes
45
+ * @param {number|null} [overrideDelay] - Optional custom delay in ms
46
+ */
47
+ resume(callback, overrideDelay = null) {
48
+ if (!this.#running && this.#remaining > 0) {
49
+ this.#startTime = Date.now();
50
+ this.#running = true;
51
+ this.#timer = setTimeout(() => {
52
+ this.#running = false;
53
+ callback?.();
54
+ }, overrideDelay ?? this.#remaining);
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Cancel the timer immediately.
60
+ */
61
+ cancel() {
62
+ clearTimeout(this.#timer);
63
+ this.#running = false;
64
+ this.#timer = null;
65
+ }
66
+
67
+ /**
68
+ * Reset the timer to its original delay, cancelling if needed.
69
+ */
70
+ reset() {
71
+ this.cancel();
72
+ this.#remaining = this.#ms;
73
+ }
74
+ }
75
+
76
+
77
+ // ./src/every.js
78
+ import { EveryTimer } from './EveryTimer.js';
79
+
80
+ /**
81
+ * Runs a function every N ms with optional execution limit.
82
+ *
83
+ * @param {string|number} duration - e.g. '500ms', 1000
84
+ * @param {Function} fn - Function to execute
85
+ * @param {number} [max=Infinity] - Max times to run
86
+ * @param {boolean} [runImmediately=false] - Run immediately on first tick
87
+ * @returns {{
88
+ * pause(): void,
89
+ * resume(): void,
90
+ * cancel(): void,
91
+ * reset(restart?: boolean): void,
92
+ * readonly isRunning: boolean,
93
+ * readonly count: number
94
+ * }}
95
+ */
96
+ export function every(duration, fn, max = Infinity, runImmediately = false) {
97
+ return new EveryTimer(duration, fn, max, runImmediately);
98
+ }
package/src/after.js ADDED
@@ -0,0 +1,84 @@
1
+ // ./src/after.js
2
+ import { parseDuration } from './parseDuration.js';
3
+
4
+ import { AfterTimer } from './AfterTimer.js';
5
+
6
+ /**
7
+ * Schedules a one-time delayed function.
8
+ *
9
+ * @param {string|number} duration - e.g. '1s', 500, '2m'
10
+ * @param {Function} fn - Main function to run
11
+ * @param {Function} [onFinish] - Optional post-run callback
12
+ * @returns {{
13
+ * pause(): void,
14
+ * resume(): void,
15
+ * cancel(): void,
16
+ * isRunning: boolean
17
+ * }}
18
+ */
19
+ export function after(duration, fn, onFinish) {
20
+ return new AfterTimer(duration, fn, onFinish);
21
+ }
22
+
23
+
24
+ /**
25
+ * Schedules a one-time delayed function.
26
+ * @param {string} duration - e.g. "5s", "500ms", "2m"
27
+ * @param {Function} fn - callback to run
28
+ * @returns {{
29
+ * pause(): void,
30
+ * resume(): void,
31
+ * cancel(): void,
32
+ * readonly isRunning: boolean,
33
+ * }}
34
+ */
35
+ export function _after(duration, fn, onFinish) {
36
+ const ms = parseDuration(duration);
37
+ let startTime = Date.now();
38
+ let remaining = ms;
39
+ let running = true;
40
+ let timer = null;
41
+
42
+ const schedule = () => {
43
+ startTime = Date.now();
44
+ timer = setTimeout(() => {
45
+ running = false;
46
+ fn?.(); // Main Func to exec after delay.
47
+ onFinish?.(); // Callback after running, if passed.
48
+ }, remaining);
49
+ };
50
+
51
+
52
+ const pause = () => {
53
+ if (running) {
54
+ clearTimeout(timer);
55
+ remaining -= Date.now() - startTime;
56
+ running = false;
57
+ }
58
+ };
59
+
60
+ const resume = () => {
61
+ if (!running && remaining > 0) {
62
+ startTime = Date.now();
63
+ running = true;
64
+ schedule();
65
+ }
66
+ };
67
+
68
+ const cancel = () => {
69
+ clearTimeout(timer);
70
+ running = false;
71
+ timer = null;
72
+ };
73
+
74
+ // Scedule Timer for execution.
75
+ schedule();
76
+
77
+ return {
78
+ pause,
79
+ resume,
80
+ cancel,
81
+ get isRunning() { return running; }
82
+ };
83
+
84
+ }
@@ -0,0 +1,17 @@
1
+ import { parseDuration } from './parseDuration.js';
2
+
3
+ /**
4
+ * Debounces a function, waiting until silence before firing.
5
+ * @param {string} duration - e.g. '300ms', '1s'
6
+ * @param {Function} fn - function to debounce
7
+ * @returns {Function} debounced function
8
+ */
9
+ export function debounce(duration, fn) {
10
+ const ms = parseDuration(duration);
11
+ let timer = null;
12
+
13
+ return (...args) => {
14
+ clearTimeout(timer);
15
+ timer = setTimeout(() => fn(...args), ms);
16
+ };
17
+ }