Skip to content

Commit

Permalink
feat(rstream): add timestamp support for fromRAF()
Browse files Browse the repository at this point in the history
- add FromRAFOpts
- update docs
  • Loading branch information
postspectacular committed Apr 8, 2023
1 parent 5e90431 commit a2b8629
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions packages/rstream/src/raf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,38 @@ import { __optsWithID } from "./idgen.js";
import { fromInterval } from "./interval.js";
import { stream } from "./stream.js";

export interface FromRAFOpts extends CommonOpts {
/**
* Browser only. If true (default: false), passes the timestamps received
* via `requestAnimationFrame()` as stream values. If false, a simple
* counter [0..∞) will be emitted.
*
* @defaultValue false
*/
timestamp: boolean;
}

/**
* Yields {@link Stream} of a monotonically increasing counter,
* triggered by a `requestAnimationFrame()` loop (only available in
* browser environments).
* Yields {@link Stream} of a monotonically increasing counter (or timestamps),
* triggered by a `requestAnimationFrame()` loop (only available in browser
* environments).
*
* @remarks
* In NodeJS, this function falls back to {@link fromInterval}, yielding
* a similar (approx. 60Hz) stream.
* In NodeJS, this function falls back to {@link fromInterval}, yielding a
* similar (approx. 60Hz) stream (the {@link FromRAFOpts.timestamp} option will
* be ignored).
*
* All subscribers to this stream will be processed during that same
* loop iteration.
* All subscribers to this stream will be processed during that same RAF loop
* iteration.
*/
export const fromRAF = (opts?: Partial<CommonOpts>) =>
export const fromRAF = (opts: Partial<FromRAFOpts> = {}) =>
isNode()
? fromInterval(16, opts)
: stream<number>((stream) => {
let i = 0;
let isActive = true;
const loop = () => {
isActive && stream.next(i++);
const loop: FrameRequestCallback = (time) => {
isActive && stream.next(opts.timestamp ? time : i++);
isActive && (id = requestAnimationFrame(loop));
};
let id = requestAnimationFrame(loop);
Expand Down

0 comments on commit a2b8629

Please sign in to comment.