Last active
August 29, 2015 14:27
-
-
Save jeromeetienne/8acc3f576ccea9a58bdd to your computer and use it in GitHub Desktop.
Overload RequestAnimationFrame to emulate a given framerate, or to hook callback pre/post every animation frames.
This file contains 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
/** | |
* Hijack requestAnimationFrame. It can add preFunction or postFunction. | |
* | |
* @constructor | |
*/ | |
var RafHijacker = function(){ | |
var originalFct = requestAnimationFrame | |
var _this = this | |
this.preFunction = null | |
this.postFunction = null | |
this.fps = -1 | |
requestAnimationFrame = function(callback){ | |
if( _this.fps === -1 ){ | |
originalFct(function(timestamp){ | |
onAnimationFrame(callback, timestamp) | |
}) | |
}else if( _this.fps > 0 ){ | |
setTimeout(function(){ | |
onAnimationFrame(callback, performance.now()) | |
}, 1000 / _this.fps) | |
}else { | |
console.assert(false) | |
} | |
} | |
return | |
function onAnimationFrame(callback, timestamp) { | |
if( _this.preFunction !== null ){ | |
_this.preFunction(timestamp) | |
} | |
callback(timestamp) | |
if( _this.postFunction !== null ){ | |
_this.postFunction(timestamp) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i made a full repository out of it. easier to publish documentations and examples. enjoy :)
https://github.com/jeromeetienne/raf-throttler.js