Skip to content

Instantly share code, notes, and snippets.

@sroucheray
Last active December 11, 2015 15:08
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sroucheray/4618690 to your computer and use it in GitHub Desktop.
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
(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);
@sroucheray
Copy link
Author

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