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', () => { ... } )
Code language: JavaScript (javascript)
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.
Example
Customize the delay based on your code needs:
const SCROLL_DELAY = 200;
window.addEventListener('scroll', () => {
_nonBlockingRepetiveFunctionCall( () => {
// Do your magic
}, SCROLL_DELAY);
});
Code language: JavaScript (javascript)
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)
}
}
Code language: JavaScript (javascript)
Enjoy!