Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created February 26, 2014 20:38
Show Gist options
  • Save jonathantneal/9238019 to your computer and use it in GitHub Desktop.
Save jonathantneal/9238019 to your computer and use it in GitHub Desktop.
requestAnimationFrame / cancelAnimationFrame polyfill
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish, Tino Zijdel, and Jonathan Neal
// MIT license
if (!window.requestAnimationFrame) (function() {
'use strict';
function requestAnimationFrame(callback) {
var
currentTime = now(),
delay = Math.max(0, 16 - (currentTime - lastTime));
lastTime = currentTime;
return setTimeout(function () {
lastTime = now();
callback(lastTime - startTime);
}, delay);
}
function cancelAnimationFrame(id) {
clearTimeout(id);
}
var
raf = 'RequestAnimationFrame',
caf = 'CancelAnimationFrame',
webkit = 'webkit',
moz = 'moz',
now = Date.now || function () {
return new Date().getTime();
},
startTime = now(),
lastTime = startTime;
window.requestAnimationFrame = window[moz + raf] || window[webkit + raf] || requestAnimationFrame;
window.cancelAnimationFrame = window[moz + caf] || window[webkit + caf] || window[webkit + 'CancelRequestAnimationFrame'] || cancelAnimationFrame;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment