Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A requestAnimationFrame like API which makes its best to maintain a specific framerate
(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);
var requestAnimationFrameAt25FPS = window.requestAnimationFrameRate(25),
handle;
function render(){
handle = requestAnimationFrameAt25FPS(render);
//do update your layout
updateLayout();
}
handle = requestAnimationFrameAt25FPS(render);
//later
cancelAnimationFrameRate(handle);
Owner

sroucheray commented Jan 16, 2015

This code makes its best to call an updateLayout() function at 25fps. Useful in some use cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment