Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Last active December 13, 2023 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/e63445fe433d98722e582bfe9de88a74 to your computer and use it in GitHub Desktop.
Save ycmjason/e63445fe433d98722e582bfe9de88a74 to your computer and use it in GitHub Desktop.
export const requestAnimationFrameRecursive = (
fn: (
highResTimestamp: DOMHighResTimeStamp,
additionalInfo: {
stop: () => void;
totalTimelapse: DOMHighResTimeStamp;
timelapseSinceLast: DOMHighResTimeStamp;
},
) => void,
o?: {
initialTimestamp: DOMHighResTimeStamp;
lastTimestamp: DOMHighResTimeStamp;
},
): (() => void) => {
let stopNext: () => void;
const stop = (): void => {
window.cancelAnimationFrame(id);
stopNext?.();
};
const id = window.requestAnimationFrame(ts => {
const initialTimestamp = o?.initialTimestamp ?? ts;
const lastTimestamp = o?.lastTimestamp ?? initialTimestamp;
// this needs to happen before calling `fn` so `stop` is defined when fn is called
stopNext = requestAnimationFrameRecursive(fn, {
initialTimestamp,
lastTimestamp: ts,
});
fn(ts, {
stop,
totalTimelapse: ts - initialTimestamp,
timelapseSinceLast: ts - lastTimestamp,
});
});
return stop;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment