Skip to content

Instantly share code, notes, and snippets.

@Philzen
Created February 18, 2013 03:59
Show Gist options
  • Save Philzen/4975041 to your computer and use it in GitHub Desktop.
Save Philzen/4975041 to your computer and use it in GitHub Desktop.
This is a sandbox to test the requestAnimationFrame Polyfill as offered by http://www.calormen.com/polyfill/. Mainly targeting Webkit 533.1 in order to gain some form of rendering framerate control on android 2 devices.
// requestAnimationFrame
// http://www.w3.org/TR/animation-timing/
(function() {
var TARGET_FPS = 60,
requests = {},
raf_handle = 1,
timeout_handle = -1;
function isVisible(element) {
return element.offsetWidth > 0 && element.offsetHeight > 0;
}
function onFrameTimer() {
var cur_requests = requests, id, request;
requests = Object.create(null);
timeout_handle = -1;
for (id in cur_requests) {
if (Object.prototype.hasOwnProperty.call(cur_requests, id)) {
request = cur_requests[id];
if (!request.element || isVisible(request.element)) {
request.callback(Date.now());
}
}
}
}
function requestAnimationFrame(callback, element) {
var cb_handle = raf_handle++;
requests[cb_handle] = {callback: callback, element: element};
if (timeout_handle === -1) {
timeout_handle = window.setTimeout(onFrameTimer, 1000 / TARGET_FPS);
}
return cb_handle;
}
function cancelAnimationFrame(handle) {
delete requests[handle];
if (Object.keys(requests).length === 0) {
window.clearTimeout(timeout_handle);
timeout_handle = -1;
}
}
window.requestAnimationFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
requestAnimationFrame;
// NOTE: Older versions of the spec called this "cancelRequestAnimationFrame"
window.cancelAnimationFrame = window.cancelRequestAnimationFrame =
window.cancelAnimationFrame || window.cancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame ||
window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
cancelAnimationFrame;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment