-
-
Save mckamey/3815604 to your computer and use it in GitHub Desktop.
requestAnimationFrame polyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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