Last active
December 12, 2024 18:57
-
-
Save justenh/5fe13a4da8d730cc6ab47fb33cf44ff1 to your computer and use it in GitHub Desktop.
Animates a function at a given FPS.
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
/** | |
* Throttles an animation callback at a specified FPS. | |
* @param {number} The target frame rate. | |
* @param {function} The callback to trigger at the specified FPS. | |
*/ | |
const animate = (fps, fn, startingFrame = 1) => { | |
const fpsInterval = 1000 / fps; | |
let then = window.performance.now(); | |
let now = then; | |
let elapsed = 0; | |
let isPlaying = true; | |
let frame = startingFrame; | |
const tick = () => { | |
now = window.performance.now(); | |
elapsed = now - then; | |
if (elapsed > fpsInterval) { | |
then = now - (elapsed % fpsInterval); | |
isPlaying = fn(frame++); | |
} | |
if (isPlaying) { | |
window.requestAnimationFrame(tick); | |
} | |
}; | |
window.requestAnimationFrame(tick); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure what the
(elapsed % fpsInterval)
really accomplishes but the original JS fiddle said that it fixed an issue with frame rates not being multiples of 16.67... I think.