How to improve formance scroll events?

This small snippet will allow you to run repetitive events without blocking the UI and improving the overall performance of the event.

When you add a scroll event listener such as:

window.addEventListener('scroll', () => { ... } )

Whatever you do on the scroll will be fired thousands of times when the user scrolls down.

Use a throttle function

It will avoid executing your code too many times possibily freezing the UI or using too much CPU.


Customize the delay based on your code needs:

const SCROLL_DELAY = 200; window.addEventListener('scroll', () => { _nonBlockingRepetiveFunctionCall( () => { // Do your magic }, SCROLL_DELAY); });

Grap the snippet

const _timeoutIDs = {} /** * @param {function} paramFunction * @param {number} timeoutMs * @param {string} [functionID] */ function nonBlockingRepetiveFunctionCall(paramFunction, timeoutMs, functionID = '') { if (!_timeoutIDs[paramFunction + functionID]) { // Add timeout to not block the UI _timeoutIDs[paramFunction + functionID] = window.setTimeout(() => { paramFunction() window.clearTimeout(_timeoutIDs[paramFunction + functionID]) _timeoutIDs[paramFunction + functionID] = undefined }, timeoutMs) } }


About Ricard Torres

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> by using this tags.