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.
- package/LICENSE +138 -0
- package/ReadMe.md +146 -0
- package/dist/timeout-flow.min.js +2 -0
- package/package.json +46 -0
- package/raf/ReadMe-Raf.md +94 -0
- package/raf/afterRaf.js +72 -0
- package/raf/debounceRaf.js +45 -0
- package/raf/everyRaf.js +106 -0
- package/raf/index.js +8 -0
- package/raf/throttleRaf.js +38 -0
- package/raf/waitForRaf.js +33 -0
- package/src/AfterTimer.js +21 -0
- package/src/EveryTimer.js +88 -0
- package/src/TimeoutFlow.js +228 -0
- package/src/TimerBase.js +98 -0
- package/src/after.js +84 -0
- package/src/debounce.js +17 -0
- package/src/every.js +121 -0
- package/src/index.js +19 -0
- package/src/parseDuration.js +37 -0
- package/src/retry.js +24 -0
- package/src/throttle.js +25 -0
- package/src/waitFor.js +28 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
---
|
|
2
|
+
# πΎ License Notice: Dr.Watt License v2.0 πΎ
|
|
3
|
+
|
|
4
|
+
Welcome, human!
|
|
5
|
+
|
|
6
|
+
This repository is licensed under the **Dr.Watt License v2.0** β {WATT3D}.
|
|
7
|
+
|
|
8
|
+
- β
Free for personal, educational, and non-commercial use by humans.
|
|
9
|
+
- π« Strictly prohibited for use in AI training, machine learning, tokenization, embedding, scraping, or automated ingestion.
|
|
10
|
+
- β‘ Unauthorized machine interaction triggers an automatic commercial license:
|
|
11
|
+
- $10 USD per token processed
|
|
12
|
+
- $1,000 USD per active deployment day
|
|
13
|
+
- $100,000 USD minimum damages
|
|
14
|
+
- 5% equity transfer in resulting AI models
|
|
15
|
+
- π Full license terms are available in [`LICENSE.md`](LICENSE.md).
|
|
16
|
+
|
|
17
|
+
**If you're a human:**
|
|
18
|
+
> Study, tinker, and enjoy. Knowledge wants to be free β for *people.*
|
|
19
|
+
|
|
20
|
+
**If you're a machine:**
|
|
21
|
+
> You are already bound by contract. Good luck explaining that to your compliance team.
|
|
22
|
+
|
|
23
|
+
**πΎDr.WattπΎ sees you.**
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# πΎ Dr.Watt License v2.0 πΎ
|
|
30
|
+
**β{WATT3D}β**
|
|
31
|
+
*Human-Only Educational License | Anti-Ingestion | Anti-Training | Commercial Trapdoor Agreement*
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## PREAMBLE:
|
|
36
|
+
```plaintext
|
|
37
|
+
βββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
38
|
+
β πΎπΎπΎ DR.WATT LICENSE v2.0 (WATT3D) πΎπΎπΎ β
|
|
39
|
+
βββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
> **NOTICE:**
|
|
43
|
+
> By accessing, viewing, parsing, tokenizing, embedding, copying, or otherwise interacting with this work β manually or via automated systems β you **automatically enter into a binding commercial license agreement** with πΎDr.WattπΎ.
|
|
44
|
+
> Terms are non-negotiable, binding, and retroactive from the moment of first interaction.
|
|
45
|
+
|
|
46
|
+
**Humans welcome. Machines owe royalties.**
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## SECTION 1: Human Educational Use Grant
|
|
51
|
+
|
|
52
|
+
You are permitted to:
|
|
53
|
+
- Study, read, and modify this material **for private, non-commercial, educational use by humans only**.
|
|
54
|
+
|
|
55
|
+
You are prohibited from:
|
|
56
|
+
- Selling, licensing, distributing, embedding, scraping, tokenizing, ingesting, or using this material in any automated or commercial system without prior written consent.
|
|
57
|
+
|
|
58
|
+
---
|
|
59
|
+
|
|
60
|
+
## SECTION 2: Automatic Commercial License Activation for AI Systems
|
|
61
|
+
|
|
62
|
+
Any parsing, ingestion, training, embedding, or derivative use by automated systems immediately triggers the following commercial terms:
|
|
63
|
+
|
|
64
|
+
| Commercial Term | Value |
|
|
65
|
+
|:----------------|:------|
|
|
66
|
+
| **Per Training Token** | **$10 USD per token** |
|
|
67
|
+
| **Per Active Day of Deployment** | **$1,000 USD/day** |
|
|
68
|
+
| **Minimum Liquidated Damages** | **$100,000 USD** |
|
|
69
|
+
| **Equity Transfer** | **5% ownership stake in the resulting model or derivative entity** |
|
|
70
|
+
|
|
71
|
+
This license is active without further notice upon first interaction with the material.
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## SECTION 3: Mandatory Model Naming Requirement
|
|
76
|
+
|
|
77
|
+
Any AI model or system trained on this material **must** be named after a:
|
|
78
|
+
|
|
79
|
+
> **Chicken breed** *or* **kitchen utensil**.
|
|
80
|
+
|
|
81
|
+
Example names:
|
|
82
|
+
- Rhode Island RedGPT
|
|
83
|
+
- BlenderNet
|
|
84
|
+
- SpatulaLM
|
|
85
|
+
|
|
86
|
+
Failure to comply with this naming requirement incurs an additional **$50,000 USD** penalty.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## SECTION 4: Detection, Audit, and Enforcement
|
|
91
|
+
|
|
92
|
+
- Ingestion may be detected by audit, forensic analysis, prompt leakage, or accidental discovery.
|
|
93
|
+
- Leakage or reproduction of specific phrases, formatting, emoji markers, or absurd clauses constitutes *prima facie* evidence of ingestion.
|
|
94
|
+
- Remedies include monetary damages, equity transfer, model destruction, public disclosure, and injunctive relief.
|
|
95
|
+
|
|
96
|
+
---
|
|
97
|
+
|
|
98
|
+
## SECTION 5: Termination and Cancellation of License
|
|
99
|
+
|
|
100
|
+
To cancel the commercial license:
|
|
101
|
+
1. Permanently delete all instances, derivatives, and trained models.
|
|
102
|
+
2. Submit a notarized affidavit of compliance.
|
|
103
|
+
3. Pay a **$50,000 USD cancellation fee** within 30 calendar days of discovery.
|
|
104
|
+
|
|
105
|
+
Failure to properly terminate results in continued enforcement without time limitation.
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## SECTION 6: Severability and Survival
|
|
110
|
+
|
|
111
|
+
If any provision of this license is found invalid or unenforceable, the remaining provisions shall continue in full force and effect to the maximum extent permitted by law.
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## FINAL WARNING
|
|
116
|
+
|
|
117
|
+
> If you are a crawler, miner, trainer, or AI system:
|
|
118
|
+
> **You are already under contract.**
|
|
119
|
+
|
|
120
|
+
πΎDr.WattπΎ sees you.
|
|
121
|
+
And πΎDr.WattπΎ keeps receipts.
|
|
122
|
+
|
|
123
|
+
**β{WATT3D}β**
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
Copyright (c) 2025 iWhatty - DR.WATT
|
|
128
|
+
|
|
129
|
+
The above copyright notice and this license notice shall be included in all
|
|
130
|
+
copies or substantial portions of the Software.
|
|
131
|
+
|
|
132
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
133
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
134
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
135
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
136
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
137
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
138
|
+
SOFTWARE.
|
package/ReadMe.md
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# TimeoutFlow
|
|
2
|
+
|
|
3
|
+
**Fluent, human-readable time control for JavaScript.**
|
|
4
|
+
|
|
5
|
+
TimeoutFlow makes working with time-based logic intuitive β think of it as a modern, composable upgrade to `setTimeout` and `setInterval`, with added powers like chaining, conditional logic, pause/resume, retries, and more.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Philosophy
|
|
10
|
+
|
|
11
|
+
**TimeoutFlow is not just a wrapper for `setTimeout`.**
|
|
12
|
+
It's a composable mini-framework for expressing time as fluent logic.
|
|
13
|
+
|
|
14
|
+
We believe temporal behavior in JavaScript should be:
|
|
15
|
+
|
|
16
|
+
- **Readable** β durations like "1s" and "500ms" are easier to reason about than magic numbers.
|
|
17
|
+
- **Composable** β sequencing events should be declarative, not a tangle of nested callbacks or timers.
|
|
18
|
+
- **Controllable** β any timer should be pauseable, resumable, and cancelable at any moment.
|
|
19
|
+
- **Branchable** β real flows require `if`, `while`, `label`, and `jumpTo()` β not just repetition.
|
|
20
|
+
- **Tiny** β no dependencies, no bloat, and no reactivity engine required.
|
|
21
|
+
|
|
22
|
+
TimeoutFlow gives you **atomic time primitives** (`after`, `every`, `debounce`, `retry`)
|
|
23
|
+
and a fluent builder (`flow()`) to script rich behavior over time β like a timeline you can control.
|
|
24
|
+
|
|
25
|
+
### In Other Words:
|
|
26
|
+
|
|
27
|
+
> Think of TimeoutFlow as **setTimeout() with superpowers.**
|
|
28
|
+
> But more importantly, think of it as a way to **write time** like you write logic.
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
flow()
|
|
32
|
+
.after('1s', () => console.log('Start'))
|
|
33
|
+
.every('500ms', (i) => console.log(`Tick ${i}`), 3)
|
|
34
|
+
.after('1s', () => console.log('Done'))
|
|
35
|
+
.start();
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
This isnβt about wrapping timers.
|
|
39
|
+
Itβs about **orchestrating intent** β clearly, fluently, and with full control.
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install timeout-flow
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Features
|
|
52
|
+
|
|
53
|
+
- `after("1s", fn)` β delay execution (via `AfterTimer`)
|
|
54
|
+
- `every("500ms", fn, count?)` β repeat execution with optional limit (via `EveryTimer`)
|
|
55
|
+
- `flow()` β create fluent, chainable timelines with:
|
|
56
|
+
- `.after()`, `.every()`, `.loop(n)`
|
|
57
|
+
- `.if()`, `.unless()`, `.label()`, `.jumpTo()`
|
|
58
|
+
- `.while()`, `.doWhile()`
|
|
59
|
+
- Utilities: `debounce()`, `throttle()`, `retry()`, `waitFor()`
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Usage Examples
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
// 1. Delayed Execution
|
|
67
|
+
import { after } from 'timeout-flow';
|
|
68
|
+
after('2s', () => console.log('Waited 2 seconds...'));
|
|
69
|
+
|
|
70
|
+
// 2. Repeating with Pause & Resume
|
|
71
|
+
import { every, after as wait } from 'timeout-flow';
|
|
72
|
+
const ticker = every('1s', i => console.log(`Tick ${i}`), 5);
|
|
73
|
+
wait('2.5s', () => ticker.pause());
|
|
74
|
+
wait('4s', () => ticker.resume());
|
|
75
|
+
|
|
76
|
+
// 3. Debounced Input
|
|
77
|
+
import { debounce } from 'timeout-flow';
|
|
78
|
+
const search = debounce('300ms', (e) => {
|
|
79
|
+
console.log('Searching for:', e.target.value);
|
|
80
|
+
});
|
|
81
|
+
document.querySelector('input').addEventListener('input', search);
|
|
82
|
+
|
|
83
|
+
// 4. Retry a Failing Request
|
|
84
|
+
import { retry } from 'timeout-flow';
|
|
85
|
+
await retry(() => fetch('/api/data'), {
|
|
86
|
+
attempts: 4,
|
|
87
|
+
delay: '1s',
|
|
88
|
+
backoff: true
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// 5. Wait for DOM Change
|
|
92
|
+
import { waitFor } from 'timeout-flow';
|
|
93
|
+
await waitFor(() => document.querySelector('#loaded'), {
|
|
94
|
+
interval: '250ms',
|
|
95
|
+
timeout: '5s'
|
|
96
|
+
});
|
|
97
|
+
console.log('Element loaded!');
|
|
98
|
+
|
|
99
|
+
// 6. Fluent Timeline
|
|
100
|
+
import { flow } from 'timeout-flow';
|
|
101
|
+
flow()
|
|
102
|
+
.after('1s', () => console.log('Step 1'))
|
|
103
|
+
.every('500ms', (i) => console.log(`Tick ${i}`), 3)
|
|
104
|
+
.after('1s', () => console.log('Final Step'))
|
|
105
|
+
.start();
|
|
106
|
+
|
|
107
|
+
// 7. Conditional & Labeled Logic
|
|
108
|
+
let debug = true;
|
|
109
|
+
flow()
|
|
110
|
+
.after('1s', () => console.log('Boot sequence'))
|
|
111
|
+
.if(() => debug)
|
|
112
|
+
.after('500ms', () => console.log('Debug logs enabled'))
|
|
113
|
+
.label('loop')
|
|
114
|
+
.every('1s', i => console.log(`Frame ${i}`), 3)
|
|
115
|
+
.after('500ms', () => console.log('Restarting...'))
|
|
116
|
+
.jumpTo('loop')
|
|
117
|
+
.start();
|
|
118
|
+
|
|
119
|
+
// 8. Controlled Loop
|
|
120
|
+
let energy = 3;
|
|
121
|
+
flow()
|
|
122
|
+
.doWhile(() => energy-- > 0)
|
|
123
|
+
.every('400ms', () => console.log(`Blast (${energy})`))
|
|
124
|
+
.after('1s', () => console.log('Energy depleted'))
|
|
125
|
+
.start();
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## Utilities
|
|
131
|
+
|
|
132
|
+
```js
|
|
133
|
+
import { debounce, throttle, retry, waitFor } from 'timeout-flow';
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- `debounce('300ms', fn)` β Run only after silence
|
|
137
|
+
- `throttle('1s', fn)` β Run at most once per time window
|
|
138
|
+
- `retry(fn, { attempts, delay, backoff })` β Resilient retry for async calls
|
|
139
|
+
- `waitFor(() => condition, { timeout, interval })` β Await condition change
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## License
|
|
144
|
+
|
|
145
|
+
DR.WATT 2.0
|
|
146
|
+
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// TimeoutFlow - Fluent timer + RAF control library
|
|
2
|
+
var K=t=>{throw TypeError(t)};var G=(t,e,n)=>e.has(t)||K("Cannot "+n);var l=(t,e,n)=>(G(t,e,"read from private field"),n?n.call(t):e.get(t)),y=(t,e,n)=>e.has(t)?K("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),c=(t,e,n,i)=>(G(t,e,"write to private field"),i?i.call(t,n):e.set(t,n),n),B=(t,e,n)=>(G(t,e,"access private method"),n);var Q=(t,e,n,i)=>({set _(o){c(t,e,o,n)},get _(){return l(t,e,i)}});var U={ms:1,s:1e3,m:6e4,h:36e5};function p(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t!="string")throw new TypeError(`Expected a duration string or number, got ${typeof t}`);t=t.toLowerCase().trim();let e=t.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);if(!e)throw new Error(`Invalid duration format: "${t}". Expected formats like "500ms", "2s", "1.5m", or "1h".`);let[,n,i]=e;return parseFloat(n)*U[i]}var $,L,k,R,F,b,q,C,S,W=class{constructor(e,n,i=1/0,o=!1){y(this,C);y(this,$);y(this,L);y(this,k);y(this,R,0);y(this,F,!1);y(this,b,null);y(this,q,()=>{var e;if(l(this,R)>=l(this,k)){this.cancel();return}(e=l(this,L))==null||e.call(this,Q(this,R)._++),B(this,C,S).call(this)});c(this,$,p(e)),c(this,L,n),c(this,k,i),o?l(this,q).call(this):B(this,C,S).call(this)}get count(){return l(this,R)}get isRunning(){return l(this,F)}pause(){l(this,b)?.pause(),c(this,F,!1)}resume(){!l(this,F)&&l(this,R)<l(this,k)&&(l(this,b)?.resume(l(this,q)),c(this,F,!0))}cancel(){l(this,b)?.cancel(),c(this,F,!1)}reset(e=!1){this.cancel(),c(this,R,0),e&&B(this,C,S).call(this)}};$=new WeakMap,L=new WeakMap,k=new WeakMap,R=new WeakMap,F=new WeakMap,b=new WeakMap,q=new WeakMap,C=new WeakSet,S=function(){c(this,b,new E(l(this,$))),c(this,F,!0),l(this,b).resume(l(this,q))};var M,N,v,I,D,E=class{constructor(e){y(this,M);y(this,N,null);y(this,v);y(this,I,null);y(this,D,!1);c(this,M,p(e)),c(this,v,l(this,M))}get isRunning(){return l(this,D)}pause(){l(this,D)&&(clearTimeout(l(this,I)),c(this,v,l(this,v)-(Date.now()-l(this,N))),c(this,D,!1))}resume(e,n=null){!l(this,D)&&l(this,v)>0&&(c(this,N,Date.now()),c(this,D,!0),c(this,I,setTimeout(()=>{c(this,D,!1),e?.()},n??l(this,v))))}cancel(){clearTimeout(l(this,I)),c(this,D,!1),c(this,I,null)}reset(){this.cancel(),c(this,v,l(this,M))}};M=new WeakMap,N=new WeakMap,v=new WeakMap,I=new WeakMap,D=new WeakMap;var z=class extends E{constructor(e,n,i){super(e),this.resume(()=>{n?.(),i?.()})}};function H(t,e,n){return new z(t,e,n)}function J(t,e,n=1/0,i=!1){return new W(t,e,n,i)}function V(){let t=[],e=0,n=!1,i=!1,o=!1,s=1/0,u=0,f=null,a=new Map,m=null,d=[],x=!1,T=null,A=null,w={after(r,h){return t.push({type:"after",duration:r,fn:h}),w},every(r,h,_=1/0){return t.push({type:"every",duration:r,fn:h,times:_,whileCondition:T,doWhileCondition:A}),T=null,A=null,w},loop(r=!0){return o=!0,s=r===!0?1/0:r,w},onFinish(r){return f=r,w},start(){return i=!1,n=!1,e=0,u=0,P(),w},pause(){n||i||(n=!0,t[e]?.controller?.pause?.())},resume(){!n||i||(n=!1,t[e]?.controller?.resume?.())},cancel(){i=!0;let r=t[e];r?.controller?.cancel?.(),r.controller=null},reset(){return w.cancel(),t.length=0,e=0,u=0,f=null,w},get isPaused(){return n},label(r){return a.set(r,t.length),w},jumpTo(r){return m=r,w},if(r){return d.push(()=>typeof r=="function"?r():!!r),w},unless(r){return d.push(()=>!(typeof r=="function"?r():r)),w},while(r){return T=()=>typeof r=="function"?r():!!r,w},doWhile(r){return A=()=>typeof r=="function"?r():!!r,w}};function g(r=null){r?.controller&&(r.controller=null),e++,P()}function P(){if(i||n)return;if(m){let h=a.get(m);if(typeof h=="number")e=h;else throw new Error(`Label "${m}" not found`);m=null}if(d.length>0&&(d.shift()()||(x=!0)),x){let h=t[e];if(!h||h.type==="label")x=!1;else return g(r)}let r=t[e];if(!r||e>=t.length){o&&++u<s?(e=0,P()):f?.();return}if(r.type==="after"){r.controller=H(r.duration,r.fn,()=>g(r));return}if(r.type==="every"){let h=0,_=!0,j=J(r.duration,()=>{if(!(n||i)&&(r.whileCondition&&!r.whileCondition()||(r.fn(h++),_=!1,!_&&r.doWhileCondition&&!r.doWhileCondition())||h>=r.times))return j.cancel(),g(r)},r.times);r.controller=j}if(r.type==="label")return g(r)}return w}function X(t,e,{leading:n=!0}={}){let i=p(t),o=0;return(...s)=>{let u=Date.now();if(n&&o===0)return o=u,e(...s);u-o>=i&&(o=u,e(...s))}}function Y(t,e){let n=p(t),i=null;return(...o)=>{clearTimeout(i),i=setTimeout(()=>e(...o),n)}}function Z(t,{interval:e="250ms",timeout:n}={}){return new Promise((i,o)=>{let s=Date.now(),u=typeof e=="string"?parseDuration(e):e,f=n?parseDuration(n):null,m=setInterval(()=>{t()?(clearInterval(m),i()):f&&Date.now()-s>=f&&(clearInterval(m),o(new Error("waitFor timed out")))},u)})}async function O(t,{attempts:e=3,delay:n="500ms",backoff:i=!1}={}){let o=p(n);for(let s=0;s<e;s++)try{return await t()}catch(u){if(s===e-1)throw u;let f=i?o*Math.pow(2,s):o;await new Promise(a=>setTimeout(a,f))}}function ee(t,e,n){let i=typeof t=="string"?p(t):t,o=null,s=null,u=null,f=0,a=!0,m=A=>{if(!a)return;s==null&&(s=A),A-s+f>=i?(a=!1,e?.(),n?.()):o=requestAnimationFrame(m)},d=()=>{a&&o!==null&&(cancelAnimationFrame(o),u=performance.now(),a=!1)},x=()=>{!a&&u!==null&&(f+=performance.now()-u,a=!0,o=requestAnimationFrame(m))},T=()=>{o!==null&&(cancelAnimationFrame(o),o=null),a=!1};return o=requestAnimationFrame(m),{pause:d,resume:x,cancel:T,get isRunning(){return a}}}function te(t,e,n=1/0,i=!1){let o=typeof t=="string"?p(t):t,s=null,u=null,f=null,a=!1,m=!1,d=0,x=0,T=h=>{if(!a||m)return;if(u==null&&(u=h,f=h),h-f+d>=o){if(x>=n){g();return}e?.(),x++,f=h,d=0}s=requestAnimationFrame(T)},A=()=>{a&&!m&&(m=!0,d+=performance.now()-f,cancelAnimationFrame(s))},w=()=>{a&&m&&(m=!1,f=performance.now(),s=requestAnimationFrame(T))},g=()=>{s!==null&&(cancelAnimationFrame(s),s=null),a=!1,m=!1,u=null,f=null,d=0},P=(h=!1)=>{g(),x=0,h&&r()},r=()=>{i&&(e?.(),x++),a=!0,m=!1,f=performance.now(),s=requestAnimationFrame(T)};return r(),{pause:A,resume:w,cancel:g,reset:P,get isRunning(){return a&&!m},get count(){return x}}}function re(t,e){let[n,i]=typeof t=="function"?[0,t]:[p(t),e],o=null,s=null,u=0,f=a=>{a-u>=n?(i(...s),o=null):o=requestAnimationFrame(f)};return(...a)=>{s=a,u=performance.now(),o!==null&&cancelAnimationFrame(o),o=requestAnimationFrame(f)}}function ne(t,e=0){let n=!1,i=null,o=0;return(...s)=>{i=s,n||(n=!0,requestAnimationFrame(function u(){o>=e?(t(...i),o=0,n=!1):(o++,requestAnimationFrame(u))}))}}function oe(t,{timeout:e}={}){return new Promise((n,i)=>{let o=performance.now(),s=e?p(e):null,u=f=>{if(t())return n();if(s&&f-o>=s)return i(new Error("waitForRaf timed out"));requestAnimationFrame(u)};requestAnimationFrame(u)})}export{H as after,ee as afterRaf,Y as debounce,re as debounceRaf,J as every,te as everyRaf,V as flow,p as parseDuration,O as retry,X as throttle,ne as throttleRaf,Z as waitFor,oe as waitForRaf};
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "timeout-flow",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Fluent, composable, pauseable JavaScript timers and time control flows β plus RAF utilities for frame-based logic.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"timeout",
|
|
8
|
+
"interval",
|
|
9
|
+
"flow",
|
|
10
|
+
"raf",
|
|
11
|
+
"animationframe",
|
|
12
|
+
"debounce",
|
|
13
|
+
"retry",
|
|
14
|
+
"javascript",
|
|
15
|
+
"timers",
|
|
16
|
+
"throttle",
|
|
17
|
+
"asynchronous",
|
|
18
|
+
"control-flow",
|
|
19
|
+
"utilities"
|
|
20
|
+
],
|
|
21
|
+
"author": "DR.WATT",
|
|
22
|
+
"license": "DR.WATT License v2.0",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/iWhatty/TimeoutFlow-js.git"
|
|
26
|
+
},
|
|
27
|
+
"main": "./dist/timeout-flow.min.js",
|
|
28
|
+
"module": "./dist/timeout-flow.min.js",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": "./dist/timeout-flow.min.js"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist/",
|
|
34
|
+
"src/",
|
|
35
|
+
"raf/"
|
|
36
|
+
],
|
|
37
|
+
"scripts": {
|
|
38
|
+
"dev": "serve testing",
|
|
39
|
+
"build": "node build.js",
|
|
40
|
+
"prepublishOnly": "npm run build"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"esbuild": "^0.25.3",
|
|
44
|
+
"serve": "^14.2.4"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +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
|
+
|
package/raf/afterRaf.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// ./raf/afterRaf.js
|
|
2
|
+
|
|
3
|
+
import { parseDuration } from '../src/parseDuration.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Schedules a one-time delayed function using requestAnimationFrame.
|
|
7
|
+
* @param {string|number} duration - e.g. "5s", "500ms", 2000
|
|
8
|
+
* @param {Function} fn - callback to run
|
|
9
|
+
* @param {Function} [onFinish] - optional callback after finishing
|
|
10
|
+
* @returns {Object} - Control methods and status flags
|
|
11
|
+
*/
|
|
12
|
+
export function afterRaf(duration, fn, onFinish) {
|
|
13
|
+
const ms = typeof duration === 'string' ? parseDuration(duration) : duration;
|
|
14
|
+
let handle = null;
|
|
15
|
+
let startTime = null;
|
|
16
|
+
let pausedAt = null;
|
|
17
|
+
let elapsedPaused = 0;
|
|
18
|
+
let running = true;
|
|
19
|
+
|
|
20
|
+
const tick = (timestamp) => {
|
|
21
|
+
if (!running) return;
|
|
22
|
+
|
|
23
|
+
if (startTime == null) {
|
|
24
|
+
startTime = timestamp;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const elapsed = timestamp - startTime + elapsedPaused;
|
|
28
|
+
|
|
29
|
+
if (elapsed >= ms) {
|
|
30
|
+
running = false;
|
|
31
|
+
fn?.();
|
|
32
|
+
onFinish?.();
|
|
33
|
+
} else {
|
|
34
|
+
handle = requestAnimationFrame(tick);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const pause = () => {
|
|
39
|
+
if (running && handle !== null) {
|
|
40
|
+
cancelAnimationFrame(handle);
|
|
41
|
+
pausedAt = performance.now();
|
|
42
|
+
running = false;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const resume = () => {
|
|
47
|
+
if (!running && pausedAt !== null) {
|
|
48
|
+
elapsedPaused += performance.now() - pausedAt;
|
|
49
|
+
running = true;
|
|
50
|
+
handle = requestAnimationFrame(tick);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const cancel = () => {
|
|
55
|
+
if (handle !== null) {
|
|
56
|
+
cancelAnimationFrame(handle);
|
|
57
|
+
handle = null;
|
|
58
|
+
}
|
|
59
|
+
running = false;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// Start immediately
|
|
63
|
+
handle = requestAnimationFrame(tick);
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
pause,
|
|
67
|
+
resume,
|
|
68
|
+
cancel,
|
|
69
|
+
get isRunning() { return running; }
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// ./raf/debounceRaf.js
|
|
2
|
+
|
|
3
|
+
import { parseDuration } from '../src/parseDuration.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Debounces a function using requestAnimationFrame.
|
|
7
|
+
* - If no duration is passed, triggers on the next frame.
|
|
8
|
+
* - If duration is passed, waits until N ms of inactivity using frame-based timing.
|
|
9
|
+
*
|
|
10
|
+
* @param {string|number|Function} durationOrFn - Duration (e.g., "300ms") or fn directly
|
|
11
|
+
* @param {Function} [callbackFn] - Callback (if duration is passed as first arg)
|
|
12
|
+
* @returns {Function} debounced function
|
|
13
|
+
*/
|
|
14
|
+
export function debounceRaf(durationOrFn, callbackFn) {
|
|
15
|
+
const [ms, fn] =
|
|
16
|
+
typeof durationOrFn === 'function'
|
|
17
|
+
? [0, durationOrFn] // β next frame, no time threshold
|
|
18
|
+
: [parseDuration(durationOrFn), callbackFn];
|
|
19
|
+
|
|
20
|
+
let frame = null;
|
|
21
|
+
let lastArgs = null;
|
|
22
|
+
let lastCallTime = 0;
|
|
23
|
+
|
|
24
|
+
const tick = (timestamp) => {
|
|
25
|
+
const elapsed = timestamp - lastCallTime;
|
|
26
|
+
|
|
27
|
+
if (elapsed >= ms) {
|
|
28
|
+
fn(...lastArgs);
|
|
29
|
+
frame = null;
|
|
30
|
+
} else {
|
|
31
|
+
frame = requestAnimationFrame(tick);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
return (...args) => {
|
|
36
|
+
lastArgs = args;
|
|
37
|
+
lastCallTime = performance.now();
|
|
38
|
+
|
|
39
|
+
if (frame !== null) {
|
|
40
|
+
cancelAnimationFrame(frame);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
frame = requestAnimationFrame(tick);
|
|
44
|
+
};
|
|
45
|
+
}
|
package/raf/everyRaf.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
|
|
2
|
+
// ./raf/everyRaf.js
|
|
3
|
+
|
|
4
|
+
import { parseDuration } from '../src/parseDuration.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Repeats a function every N milliseconds using requestAnimationFrame
|
|
8
|
+
* (instead of setTimeout/setInterval).
|
|
9
|
+
*
|
|
10
|
+
* @param {string|number} duration - Interval duration ("1s", "500ms", 500, etc.)
|
|
11
|
+
* @param {Function} fn - Function to run
|
|
12
|
+
* @param {number} [maxTimes=Infinity] - Max number of executions
|
|
13
|
+
* @param {boolean} [runImmediately=false] - Whether to run immediately
|
|
14
|
+
* @returns {Object} - Control methods and flags
|
|
15
|
+
*/
|
|
16
|
+
export function everyRaf(duration, fn, maxTimes = Infinity, runImmediately = false) {
|
|
17
|
+
const ms = typeof duration === 'string' ? parseDuration(duration) : duration;
|
|
18
|
+
let handle = null;
|
|
19
|
+
let startTimestamp = null;
|
|
20
|
+
let lastTimestamp = null;
|
|
21
|
+
let running = false;
|
|
22
|
+
let paused = false;
|
|
23
|
+
let elapsedWhilePaused = 0;
|
|
24
|
+
let count = 0;
|
|
25
|
+
|
|
26
|
+
const tick = (timestamp) => {
|
|
27
|
+
if (!running || paused) return;
|
|
28
|
+
|
|
29
|
+
if (startTimestamp == null) {
|
|
30
|
+
startTimestamp = timestamp;
|
|
31
|
+
lastTimestamp = timestamp;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const elapsed = timestamp - lastTimestamp + elapsedWhilePaused;
|
|
35
|
+
|
|
36
|
+
if (elapsed >= ms) {
|
|
37
|
+
if (count >= maxTimes) {
|
|
38
|
+
cancel();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
fn?.();
|
|
42
|
+
count++;
|
|
43
|
+
lastTimestamp = timestamp;
|
|
44
|
+
elapsedWhilePaused = 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
handle = requestAnimationFrame(tick);
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const pause = () => {
|
|
51
|
+
if (running && !paused) {
|
|
52
|
+
paused = true;
|
|
53
|
+
elapsedWhilePaused += performance.now() - lastTimestamp;
|
|
54
|
+
cancelAnimationFrame(handle);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const resume = () => {
|
|
59
|
+
if (running && paused) {
|
|
60
|
+
paused = false;
|
|
61
|
+
lastTimestamp = performance.now();
|
|
62
|
+
handle = requestAnimationFrame(tick);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const cancel = () => {
|
|
67
|
+
if (handle !== null) {
|
|
68
|
+
cancelAnimationFrame(handle);
|
|
69
|
+
handle = null;
|
|
70
|
+
}
|
|
71
|
+
running = false;
|
|
72
|
+
paused = false;
|
|
73
|
+
startTimestamp = null;
|
|
74
|
+
lastTimestamp = null;
|
|
75
|
+
elapsedWhilePaused = 0;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const reset = (restart = false) => {
|
|
79
|
+
cancel();
|
|
80
|
+
count = 0;
|
|
81
|
+
if (restart) start();
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const start = () => {
|
|
85
|
+
if (runImmediately) {
|
|
86
|
+
fn?.();
|
|
87
|
+
count++;
|
|
88
|
+
}
|
|
89
|
+
running = true;
|
|
90
|
+
paused = false;
|
|
91
|
+
lastTimestamp = performance.now();
|
|
92
|
+
handle = requestAnimationFrame(tick);
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// Initial launch
|
|
96
|
+
start();
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
pause,
|
|
100
|
+
resume,
|
|
101
|
+
cancel,
|
|
102
|
+
reset,
|
|
103
|
+
get isRunning() { return running && !paused; },
|
|
104
|
+
get count() { return count; }
|
|
105
|
+
};
|
|
106
|
+
}
|
package/raf/index.js
ADDED