Skip to content

Instantly share code, notes, and snippets.

@culttm
Created September 10, 2017 00:50
Show Gist options
  • Save culttm/eafa67a480f12fe05dbfcc0e8528e522 to your computer and use it in GitHub Desktop.
Save culttm/eafa67a480f12fe05dbfcc0e8528e522 to your computer and use it in GitHub Desktop.
limitLoop
var limitLoop = function (fn, fps) {
// Use var then = Date.now(); if you
// don't care about targetting < IE9
var then = new Date().getTime();
// custom fps, otherwise fallback to 60
fps = fps || 60;
var interval = 1000 / fps;
return (function loop(time){
requestAnimationFrame(loop);
// again, Date.now() if it's available
var now = new Date().getTime();
var delta = now - then;
if (delta > interval) {
// Update time
// now - (delta % interval) is an improvement over just
// using then = now, which can end up lowering overall fps
then = now - (delta % interval);
// call the fn
fn();
}
}(0));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment