-
-
Save jeongsd/c95123d73085af046f236cd63760c004 to your computer and use it in GitHub Desktop.
Limit the frame-rate being targeted with requestAnimationFrame
This file contains 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
/* | |
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