Skip to content

Instantly share code, notes, and snippets.

@jeongsd
Forked from addyosmani/limitLoop.js
Last active March 5, 2017 14:01
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 jeongsd/c95123d73085af046f236cd63760c004 to your computer and use it in GitHub Desktop.
Save jeongsd/c95123d73085af046f236cd63760c004 to your computer and use it in GitHub Desktop.
Limit the frame-rate being targeted with requestAnimationFrame
/*
http://cssdeck.com/labs/embed/gvxnxdrh/0/output
http://codetheory.in/controlling-the-frame-rate-with-requestanimationframe/
*/
class AnimationFrame {
constructor(fps = 60, animate) {
this.requestID = 0;
this.fps = fps;
this.animate = animate;
}
start() {
let then = performance.now();
const interval = 1000 / this.fps;
const animateLoop = (now) => {
this.requestID = requestAnimationFrame(animateLoop);
const delta = now - then;
if (delta > interval) {
then = now - (delta % interval);
this.animate(delta);
}
};
this.requestID = requestAnimationFrame(animateLoop);
}
stop() {
cancelAnimationFrame(this.requestID);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment