Skip to content

Instantly share code, notes, and snippets.

@fearphage
Forked from getify/1.js
Last active December 14, 2015 19:28
Show Gist options
  • Save fearphage/5136300 to your computer and use it in GitHub Desktop.
Save fearphage/5136300 to your computer and use it in GitHub Desktop.
(function(window) {
var
requestAnimationFrame = window.requestAnimationFrame
|| window.msRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.oRequestAnimationFrame
,cancelAnimationFrame = window.cancelAnimationFrame
|| window.msCancelAnimationFrame
|| window.msCancelRequestAnimationFrame
|| window.mozCancelAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.webkitCancelAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| window.oCancelAnimationFrame
|| window.oCancelRequestAnimationFrame
,requestEachAnimationFrame = window.requestEachAnimationFrame
|| window.msRequestEachAnimationFrame
|| window.mozRequestEachAnimationFrame
|| window.webkitRequestEachAnimationFrame
|| window.oRequestEachAnimationFrame
,cancelEachAnimationFrame = window.cancelEachAnimationFrame
|| window.msCancelEachAnimationFrame
|| window.msCancelRequestEachAnimationFrame
|| window.mozCancelEachAnimationFrame
|| window.mozCancelRequestEachAnimationFrame
|| window.webkitCancelEachAnimationFrame
|| window.webkitCancelRequestEachAnimationFrame
|| window.oCancelEachAnimationFrame
|| window.oCancelRequestEachAnimationFrame
,uids = {}
;
function UID() {
var uid;
do {
uid = Math.floor(Math.random() * 1e9);
} while (uid in uids);
return uid;
}
if (requestAnimationFrame && !requestEachAnimationFrame) {
window.requestEachAnimationFrame = function(fn) {
var uid = UID();
uids[uid] = requestAnimationFrame(function do_requestAnimationFrame() {
uids[uid] = requestAnimationFrame(do_requestAnimationFrame);
fn.apply(window, arguments);
});
return uid;
};
}
if (cancelAnimationFrame && !cancelEachAnimationFrame) {
window.cancelEachAnimationFrame = function(uid) {
if (uid in uids) {
cancelAnimationFrame(uids[uid]);
delete uids[uid];
}
};
}
})(this);
// how to use
var count = 0;
var id = requestEachAnimationFrame(function() {
if (++count >= 100) {
cancelEachAnimationFrame(id);
console.log("100 animation frames processed");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment