-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(rstream): add fromRAF() fallback for node, add docs
- Loading branch information
1 parent
592a242
commit 4e5a2ee
Showing
1 changed file
with
25 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,29 @@ | ||
import { isNode } from "@thi.ng/checks/is-node"; | ||
|
||
import { Stream } from "../stream"; | ||
import { fromInterval } from "./interval"; | ||
|
||
/** | ||
* Yields a stream of monotonically increasing counter, | ||
* triggered by a `requestAnimationFrame()` loop. | ||
* Only available in browser environments. In NodeJS, | ||
* this function falls back to `fromInterval(16)`, yielding | ||
* a similar (approximately 60fps) stream. | ||
* | ||
* Subscribers to this stream will be processed during | ||
* that same loop iteration. | ||
*/ | ||
export function fromRAF() { | ||
return new Stream<number>((o) => { | ||
let i = 0, id, | ||
isActive = true, | ||
loop = () => { | ||
isActive && o.next(i++); | ||
isActive && (id = requestAnimationFrame(loop)); | ||
}; | ||
id = requestAnimationFrame(loop); | ||
return () => (isActive = false, cancelAnimationFrame(id)); | ||
}, `raf-${Stream.NEXT_ID++}`); | ||
return isNode() ? | ||
fromInterval(16) : | ||
new Stream<number>((o) => { | ||
let i = 0, id, | ||
isActive = true, | ||
loop = () => { | ||
isActive && o.next(i++); | ||
isActive && (id = requestAnimationFrame(loop)); | ||
}; | ||
id = requestAnimationFrame(loop); | ||
return () => (isActive = false, cancelAnimationFrame(id)); | ||
}, `raf-${Stream.NEXT_ID++}`); | ||
} |