Skip to content

Instantly share code, notes, and snippets.

@jeromeetienne
Last active August 29, 2015 14:27
Show Gist options
  • Save jeromeetienne/8acc3f576ccea9a58bdd to your computer and use it in GitHub Desktop.
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.
/**
* 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)
}
}
}
@jeromeetienne
Copy link
Author

i made a full repository out of it. easier to publish documentations and examples. enjoy :)

https://github.com/jeromeetienne/raf-throttler.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment