Created
September 10, 2017 00:50
-
-
Save culttm/eafa67a480f12fe05dbfcc0e8528e522 to your computer and use it in GitHub Desktop.
limitLoop
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
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