Skip to content

Instantly share code, notes, and snippets.

@mckamey
Forked from paulirish/rAF.js
Created October 2, 2012 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mckamey/3815604 to your computer and use it in GitHub Desktop.
Save mckamey/3815604 to your computer and use it in GitHub Desktop.
requestAnimationFrame 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 and Tino Zijdel
// perf improvements by Stephen McKamey
(function(window) {
'use strict';
/**
* vendor prefixes
* @type {Array}
*/
var vendors = ['webkit', 'moz', 'ms', 'o'];
while (vendors.length && !window.requestAnimationFrame) {
/**
* next vendor prefix to test
* @type {String}
*/
var prefix = vendors.pop();
window.requestAnimationFrame = window[prefix+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[prefix+'CancelAnimationFrame'] ||
window[prefix+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
/**
* cap the framerate at 60Hz
* @const
* @type {number}
*/
var DELAY = 1000/60;
/**
* ID of the last tween
* @type {number}
*/
var _id = 0;
/**
* Timestamp of last call
* @type {number}
*/
var _last = 0;
window.requestAnimationFrame =
/**
* @param callback {function} the animation tweening
*/
function(callback) {
var now = +(new Date());
var delay = Math.max(0, DELAY - (now - _last));
_last = now + delay;
return (_id = setTimeout(callback, delay));
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment