Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.