public
Last active

requestAnimationFrame polyfill

  • Download Gist
rAF.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
// requestAnimationFrame polyfill by @rma4ok
!function (window) {
var
equestAnimationFrame = 'equestAnimationFrame',
requestAnimationFrame = 'r' + equestAnimationFrame,
 
ancelAnimationFrame = 'ancelAnimationFrame',
cancelAnimationFrame = 'c' + ancelAnimationFrame,
 
expectedTime = 0,
vendors = ['moz', 'ms', 'o', 'webkit'],
vendor;
 
while (!window[requestAnimationFrame] && (vendor = vendors.pop())) {
window[requestAnimationFrame] = window[vendor + 'R' + equestAnimationFrame];
window[cancelAnimationFrame] =
window[vendor + 'C' + ancelAnimationFrame] ||
window[vendor + 'CancelR' + equestAnimationFrame];
}
 
if (!window[requestAnimationFrame]) {
window[requestAnimationFrame] = function (callback) {
var
currentTime = +new Date,
adjustedDelay = 16 - (currentTime - expectedTime),
delay = adjustedDelay > 0 ? adjustedDelay : 0;
 
expectedTime = currentTime + delay;
 
return setTimeout(function () {
callback(expectedTime);
}, delay);
};
 
window[cancelAnimationFrame] = clearTimeout;
}
}(this);

Mind helping me understand the reason behind this?

  equestAnimationFrame = 'equestAnimationFrame',
  requestAnimationFrame = 'r' + equestAnimationFrame,

looks odd :)

@wamatt for better minification i would say...

and why use !function in the first line? :)

@ddon calling an anonymous function the bang converts it to an expression from a function declaration.

Mhh, since +new Date is slower than (new Date).getTime(). I would recommend to use the latter. http://jsperf.com/date-now-vs-date-gettime/6

...and by the way, most modern browsers (i.e. IE9+) support Date.now() so we can use it and fallback to getTime().

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.