Skip to content

Instantly share code, notes, and snippets.

@getify
Last active December 14, 2015 18:38
Show Gist options
  • Save getify/5130304 to your computer and use it in GitHub Desktop.
Save getify/5130304 to your computer and use it in GitHub Desktop.
requestEachAnimationFrame hopeful-fill.
(function(){
var
rAF = (window.requestAnimationFrame || window.msRequestAnimationFrame ||
window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ||
window.oRequestAnimationFrame),
cAF = (window.cancelAnimationFrame ||
window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame ||
window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame ||
window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame ||
window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame),
rEAF = (window.requestEachAnimationFrame || window.msRequestEachAnimationFrame ||
window.mozRequestEachAnimationFrame || window.webkitRequestEachAnimationFrame ||
window.oRequestEachAnimationFrame),
cEAF = (window.cancelEachAnimationFrame ||
window.msCancelEachAnimationFrame || window.msCancelRequestEachAnimationFrame ||
window.mozCancelEachAnimationFrame || window.mozCancelRequestEachAnimationFrame ||
window.webkitCancelEachAnimationFrame || window.webkitCancelRequestEachAnimationFrame ||
window.oCancelEachAnimationFrame || window.oCancelRequestEachAnimationFrame),
q_ids = {}
;
function qID(){
var id;
do {
id = Math.floor(Math.random() * 1E9);
} while (id in q_ids);
return id;
}
if (rAF && !rEAF) {
window.requestEachAnimationFrame = function(fn) {
var qid = qID();
q_ids[qid] = rAF(function do_rAF(){
q_ids[qid] = rAF(do_rAF);
fn.apply(window,arguments);
});
return qid;
};
}
if (cAF && !cEAF) {
window.cancelEachAnimationFrame = function(qid) {
if (qid in q_ids) {
cAF(q_ids[qid]);
delete q_ids[qid];
}
};
}
})();
// how to use
var count = 0;
var id = requestEachAnimationFrame(function(){
if (++count >= 100) {
cancelEachAnimationFrame(id);
console.log("100 animation frames processed");
}
});
@getify
Copy link
Author

getify commented Mar 11, 2013

@paulirish -- thanks for the prefix tips. and i initially called it a "prollyfill" but then people asked if it was already a planned API and i realized i might have been too eager, so I dialed it back to "hopeful-fill". :)

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