Skip to content

Instantly share code, notes, and snippets.

@Danziger
Forked from paulirish/rAF.js
Last active August 29, 2015 14:03
Show Gist options
  • Save Danziger/fc83f1b2f16f70655a4a to your computer and use it in GitHub Desktop.
Save Danziger/fc83f1b2f16f70655a4a to your computer and use it in GitHub Desktop.
// requestAnimationFrame POLYFILL ////////////////////////////////////////////////////////////////////
// requestAnimationFrame and cancelAnimationFrame polyfill based on Erik Möller's one: https://gist.github.com/paulirish/1579671
// MDN Docs: https://developer.mozilla.org/es/docs/DOM/window.requestAnimationFrame
// @source https://gist.github.com/Danziger/fc83f1b2f16f70655a4a
// @license MIT license
(function(strict, calculations){
"use strict";
var vendors = ['webkit', 'moz', 'ms', 'o'];
// Try to find the vendor's version:
for(var i = 0, L= vendors.length; !window.requestAnimationFrame && i<L; ++i) {
window.requestAnimationFrame = window[vendors[i]+'RequestAnimationFrame'];
}
window.cancelAnimationFrame = window.cancelAnimationFrame?window.cancelAnimationFrame:(window[vendors[i]+'CancelAnimationFrame'] || window[vendors[i]+'CancelRequestAnimationFrame']);
// If there is no requestAnimationFrame yet or it is there, but there is no cancelAnimationFrame and we prefer to have both implemented with timers:
if (!window.requestAnimationFrame || (!window.cancelAnimationFrame && strict)){
var lastTime = 0;
if(calculations){ // setTimeout version with calculations:
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
else{ // simplier setTimeout version without calculations (less overhead):
window.requestAnimationFrame = function(callback, element){
var id = window.setTimeout(function(){
callback(+new Date);
}, 1000 / 60);
return id;
};
}
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
})(false, false); // (strict, calculations)
/*
strict = false
We will have a requestAnimationFrame but cancelAnimationFrame is not guaranteed.
strict = true
We will always have a requestAnimationFrame and a cancelAnimationFrame, but they may be
implemented using setTimeout even thought there's a specific vendor's version of
requestAnimationFrame (but not of cancelAnimationFrame).
calculations = false
If setTimeout is used, it will have a constant time between calls (1000/60).
calculations = true
If setTimeout is used, it will do some calculations to determine the time between calls.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment