public
Last active

A requestAnimationFrame like API which makes its best to maintain a specific framerate

  • Download Gist
request-animation-frame-rate.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
(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);
usage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13
var requestAnimationFrameAt25FPS = window.requestAnimationFrameRate(25),
handle;
function render(){
handle = requestAnimationFrameAt25FPS(render);
//do update your layout
updateLayout();
}
 
handle = requestAnimationFrameAt25FPS(render);
 
 
//later
cancelAnimationFrameRate(handle);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.