Last active
June 10, 2024 20:05
-
-
Save mimshins/c331fc1a2e0e221301cfaf2c543feb80 to your computer and use it in GitHub Desktop.
Animation Loop
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 type FrameTicker = (deltaTime: number) => void; | |
| /** | |
| * Creates smooth animation frames. | |
| * | |
| * @param frameTicker This callback will be called on each frame.\ | |
| * The `deltaTime` argument specifies the time elapsed between the last frame | |
| * and the one preceding it (in milliseconds). | |
| * @returns Returns animation frames controller. | |
| */ | |
| const createAnimationFrames = (frameTicker: FrameTicker) => { | |
| let prevTimestamp: number = -Infinity; | |
| let rafReference: number = -Infinity; | |
| const mainTicker: FrameRequestCallback = timestamp => { | |
| const deltaTime = timestamp - prevTimestamp; | |
| prevTimestamp = timestamp; | |
| frameTicker(deltaTime); | |
| rafReference = window.requestAnimationFrame(mainTicker); | |
| }; | |
| const start = () => { | |
| prevTimestamp = performance.now(); | |
| rafReference = window.requestAnimationFrame(mainTicker); | |
| }; | |
| const stop = () => { | |
| window.cancelAnimationFrame(rafReference); | |
| }; | |
| return { start, stop }; | |
| }; | |
| export default createAnimationFrames; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment