Skip to content

Instantly share code, notes, and snippets.

@devnix
Last active December 13, 2016 16:02
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 devnix/fe69b5f5f2fac55d11c8b118b4d17e8c to your computer and use it in GitHub Desktop.
Save devnix/fe69b5f5f2fac55d11c8b118b4d17e8c to your computer and use it in GitHub Desktop.
Snippet for easily using requestAnimationFrame with browser events

Usage

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');
/**
* @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