Skip to content

Instantly share code, notes, and snippets.

@harrisjose
Created September 5, 2019 05:45
Show Gist options
  • Save harrisjose/37461960f30e1ec1b435c3d411ca96f7 to your computer and use it in GitHub Desktop.
Save harrisjose/37461960f30e1ec1b435c3d411ca96f7 to your computer and use it in GitHub Desktop.
RAF based debounce from github.com/WickyNilliams/headroom.js
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
/**
* Handles debouncing of events via requestAnimationFrame
* @see http://www.html5rocks.com/en/tutorials/speed/animations/
* @param {Function} callback The callback to handle whichever event
*/
function Debouncer (callback) {
this.callback = callback;
this.ticking = false;
}
Debouncer.prototype = {
constructor : Debouncer,
/**
* dispatches the event to the supplied callback
* @private
*/
update : function() {
this.callback && this.callback();
this.ticking = false;
},
/**
* ensures events don't get stacked
* @private
*/
requestTick : function() {
if(!this.ticking) {
requestAnimationFrame(this.rafCallback || (this.rafCallback = this.update.bind(this)));
this.ticking = true;
}
},
/**
* Attach this as the event listeners
*/
handleEvent : function() {
this.requestTick();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment