Skip to content

Instantly share code, notes, and snippets.

@6174
Last active December 20, 2015 09:58
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 6174/6111637 to your computer and use it in GitHub Desktop.
Save 6174/6111637 to your computer and use it in GitHub Desktop.
动画主循环!!
// see http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// shim layer with setTimeout fallback
(function(){
// chrome shipped without the time arg in m10
var timeundefined = false;
if (window.webkitRequestAnimationFrame){
webkitRequestAnimationFrame(function(time){
timeundefined = (time == undefined);
});
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
(!timeundefined && window.webkitRequestAnimationFrame) ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback, element){
return window.setTimeout(function(){
callback(+new Date);
}, 1000 / 60);
};
})();
})();
window.clearRequestTimeout = function(id) {
window.cancelAnimationFrame ? window.cancelAnimationFrame(id) :
window.webkitCancelAnimationFrame ? window.webkitCancelAnimationFrame(id) :
window.webkitCancelRequestAnimationFrame ? window.webkitCancelRequestAnimationFrame(id) : /* Support for legacy API */
window.mozCancelRequestAnimationFrame ? window.mozCancelRequestAnimationFrame(id) :
window.oCancelRequestAnimationFrame ? window.oCancelRequestAnimationFrame(id) :
window.msCancelRequestAnimationFrame ? window.msCancelRequestAnimationFrame(id) :
clearTimeout(id);
};
//or in this way
var _reqAnimFrame = window.requestAnimationFrame,
_cancelAnimFrame = window.cancelAnimationFrame,
_getTime = Date.now || function() {
return new Date().getTime();
};
//now try to determine the requestAnimationFrame and cancelAnimationFrame functions and if none are found, we'll use a setTimeout()/clearTimeout() polyfill.
a = ["ms", "moz", "webkit", "o"];
i = a.length;
while (--i > -1 && !_reqAnimFrame) {
_reqAnimFrame = window[a[i] + "RequestAnimationFrame"];
_cancelAnimFrame = window[a[i] + "CancelAnimationFrame"] || window[a[i] + "CancelRequestAnimationFrame"];
}
function Animation() {
this.animeId;
this.startAnimation = function() {
var self = this;
self.lastTime = +new Date();
self.animeId = requestAnimFrame(function( time ) {
var delayTime = time - self.lastTime;
// doSomething( delayTime ); // do some paint and calculate
console.log( delayTime );
self.startAnimation();
});
},
this.stopAnimation = function() {
clearRequestTimeout( this.animeId );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment