Skip to content

Instantly share code, notes, and snippets.

@brysonian
Last active May 26, 2020 19:14
Show Gist options
  • Save brysonian/66caa5a3e22c5dc7729cc9e69b8ae207 to your computer and use it in GitHub Desktop.
Save brysonian/66caa5a3e22c5dc7729cc9e69b8ae207 to your computer and use it in GitHub Desktop.
Simple wrapper for requestAnimationFrame that adds fps and stop/resume functionality
/*
USAGE:
Pass a function and a fraemrate to the animate function to start. This returns an object with `stop` and `resume` methods.
function draw() {
// do something in here...
}
var animator = animate(draw, 30);
...
animator.stop();
...
animator.resume();
*/
function animate(func, fps) {
fps = fps || 30;
var last = Date.now();
var rafid = false;
var tick = function() {
rafid = requestAnimationFrame(tick);
var interval = 1000/fps;
var now = Date.now();
var elapsed = now - last;
if (elapsed > interval) {
last = now;
func();
}
}
tick();
return {
stop:function() {
cancelAnimationFrame(rafid);
rafid = false;
},
resume:function() {
if (rafid === false)
tick();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment