Skip to content

Instantly share code, notes, and snippets.

@kevinchappell
Created September 28, 2018 21:17
Show Gist options
  • Save kevinchappell/0269cc00247cbec3ac3a314cedc4c3cc to your computer and use it in GitHub Desktop.
Save kevinchappell/0269cc00247cbec3ac3a314cedc4c3cc to your computer and use it in GitHub Desktop.
Throttle class
/**
* Throttle class provides and easy way for binding
* and throttling events. Helpful for events like window
* scroll that are fired often.
*/
export class Throttle {
/**
* Add an event and register callbacks
* @param {String} event
* @param {Function} cb
* @param {Object} elem DOM element we are binging to
* @return {Function} throttled cb
*/
add(event, cb, elem = window) {
const events = this
events[event] = events[event] || { callbacks: [] }
events.addCallback(event, cb)
const callback = function(evt) {
events.throttle(events[event], evt)
}
elem.addEventListener(event, callback)
return callback
}
/**
* Adds a callback to an array of callbacks for an event
* @param {String} event
* @param {Function} cb
*/
addCallback(event, cb) {
const events = this
if (cb) {
events[event].callbacks.push(cb)
}
}
/**
* Run the callbacks for a specific event
* @param {Object} event
* @param {Object} evt response from fired event
*/
runCallbacks(event, evt) {
event.callbacks.forEach(function(callback) {
callback(evt)
})
event.running = false
}
/**
* Throttle an event
* @param {Object} event in queue
* @param {Object} evt response from fired event
*/
throttle(event, evt) {
const events = this
if (!event.running) {
event.running = true
if (window.requestAnimationFrame) {
window.requestAnimationFrame(function() {
events.runCallbacks(event, evt)
})
} else {
setTimeout(events.runCallbacks.bind(event), 66)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment