Last active
December 13, 2023 23:27
-
-
Save ycmjason/e63445fe433d98722e582bfe9de88a74 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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