Skip to content

Commit

Permalink
feat(rstream): add fromRAF() fallback for node, add docs
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 25, 2018
1 parent 592a242 commit 4e5a2ee
Showing 1 changed file with 25 additions and 10 deletions.
35 changes: 25 additions & 10 deletions packages/rstream/src/from/raf.ts
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++}`);
}

0 comments on commit 4e5a2ee

Please sign in to comment.