Skip to content

Instantly share code, notes, and snippets.

@justenh
Last active December 12, 2024 18:57
Show Gist options
  • Save justenh/5fe13a4da8d730cc6ab47fb33cf44ff1 to your computer and use it in GitHub Desktop.
Save justenh/5fe13a4da8d730cc6ab47fb33cf44ff1 to your computer and use it in GitHub Desktop.
Animates a function at a given FPS.
/**
* 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);
};
@justenh
Copy link
Author

justenh commented Jul 27, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment