This utility has now its own repo https://github.com/sroucheray/requestAnimationFrameRate
You can install it via npm
or bower
Last active
December 11, 2015 15:08
-
-
Save sroucheray/4618690 to your computer and use it in GitHub Desktop.
A requestAnimationFrame like API which makes its best to maintain a specific framerate
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
(function(window) { | |
var maxFPS = 60; | |
window.requestAnimationFrameRate = function(fps) { | |
var period, | |
starter, | |
limit, | |
jitter; | |
if (typeof fps !== 'number') { | |
fps = maxFPS; | |
}else{ | |
fps = Math.max(1, Math.min(maxFPS, fps)); | |
} | |
period = 1000 / fps; | |
jitter = period * 0.1; | |
limit = period - jitter; | |
function requestAnimationFrameAtFPS(renderFrameCallBack) { | |
return (function() { | |
var handle; | |
function renderer(time) { | |
var lastPeriod; | |
starter = starter || time; | |
lastPeriod = time - starter; | |
if (lastPeriod < limit) { | |
handle = window.requestAnimationFrame(renderer); | |
} else { | |
renderFrameCallBack(time); | |
starter = time; | |
} | |
} | |
handle = window.requestAnimationFrame(renderer); | |
return function() { | |
window.cancelAnimationFrame(handle); | |
}; | |
})(); | |
} | |
return requestAnimationFrameAtFPS; | |
}; | |
window.cancelAnimationFrameRate = function(handle) { | |
handle(); | |
}; | |
})(window); |
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
var requestAnimationFrameAt25FPS = window.requestAnimationFrameRate(25), | |
handle; | |
function render(){ | |
handle = requestAnimationFrameAt25FPS(render); | |
//do update your layout | |
updateLayout(); | |
} | |
handle = requestAnimationFrameAt25FPS(render); | |
//later | |
cancelAnimationFrameRate(handle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code makes its best to call an
updateLayout()
function at 25fps. Useful in some use cases.