Last active
May 26, 2020 19:14
-
-
Save brysonian/66caa5a3e22c5dc7729cc9e69b8ae207 to your computer and use it in GitHub Desktop.
Simple wrapper for requestAnimationFrame that adds fps and stop/resume functionality
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
/* | |
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