var OptimizedEvent = require('optimizedEvent');
var optimizedEvent = new OptimizedEvent();
optimizedEvent.add(function() {
console.log('requestAnimationFrame\'d scroll :-D');
}, 'scroll');
optimizedEvent.add(function() {
console.log('requestAnimationFrame\'d resize B-)');
}, 'resize');
Last active
December 13, 2016 16:02
-
-
Save devnix/fe69b5f5f2fac55d11c8b118b4d17e8c to your computer and use it in GitHub Desktop.
Snippet for easily using requestAnimationFrame with browser events
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
/** | |
* @constructor | |
*/ | |
function OptimizedEvent() { | |
this.callbacks = []; | |
this.running = false; | |
} | |
/** | |
* @public | |
* @param {callback} Function to execute method | |
* @param {string} Name of the event | |
*/ | |
OptimizedEvent.prototype.add = function add(callback, event) { | |
if (!this.callbacks.length) { | |
window.addEventListener(event, this.eventFire.bind(this)); | |
} | |
this.addCallback(callback); | |
}; | |
/** | |
* @private | |
* Adds callback to loop | |
*/ | |
OptimizedEvent.prototype.addCallback = function addCallback(callback) { | |
if (callback) { | |
this.callbacks.push(callback); | |
} | |
}; | |
/** | |
* @private | |
* Run the actual callbacks | |
*/ | |
OptimizedEvent.prototype.runCallbacks = function runCallbacks() { | |
this.callbacks.forEach(function(callback) { | |
callback(); | |
}); | |
this.running = false; | |
}; | |
/** | |
* @private | |
* Fired on resize event | |
*/ | |
OptimizedEvent.prototype.eventFire = function eventFire() { | |
if (!this.running) { | |
this.running = true; | |
if (window.requestAnimationFrame) { | |
window.requestAnimationFrame(this.runCallbacks.bind(this)); | |
} else { | |
setTimeout(this.runCallbacks, 66); | |
} | |
} | |
}; | |
module.exports = OptimizedEvent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment