Created
September 5, 2019 05:45
-
-
Save harrisjose/37461960f30e1ec1b435c3d411ca96f7 to your computer and use it in GitHub Desktop.
RAF based debounce from github.com/WickyNilliams/headroom.js
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
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