Reputation: 5200
I have an event listener for scroll events that fires a function responsible for appending an element to the viewport. That same scroll event listener is being throttled to prevent a downpour of scroll events (more manageable). The library being used to throttle is throttle-debounce
. Problem: throttling handlePageScroll
is throttling everything contained in that method (of course).
Code:
componentDidMount() {
window.addEventListener('scroll', throttle(2000, this.handlePageScroll));
}
handlePageScroll = () => {
someFn() // logic for appending an element, does not need throttling
this.loadNextBatch(); // logic that actually needs to be throttled
};
I've tried throttling from within handlePageScroll
with no success. Is there way to fire two functions from an event listener?
Thank you in advance.
Upvotes: 2
Views: 176
Reputation: 5265
Here is a solution, by keeping a state:
componentDidMount() {
let throttled = false
window.addEventListener('scroll', () => {
if (!throttled) {
throttle(2000, () => {
this.loadNextBatch()
throttled = false
})()
throttled = true
}
someFn()
})
}
Upvotes: 1