Event handler from JavaScript will be fired every time trigger condition matched. And on resize event it could match and fire when change size of one pixel. So, event will be fired too many times and it bricks browser performance.
How to prevent resize event from firing multiple times
I think the best way is using debounce function.
What is debounce function?
Debounce function it limits the rate at which a function can fire. A quick example: you have a resize listener on the window which does some element dimension calculations and (possibly) repositions a few elements. That isn’t a heavy task in itself but being repeatedly fired after numerous resizes will really slow your site down.
Example of using debounce function
Returns a function, that as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If `immediate` is passed, trigger the function on the leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Code language: JavaScript (javascript)
Pass the debounce function the function to execute and the fire rate limit in milliseconds. Here’s an example usage:
var handleResize = debounce(function() {
// Your tuff here
}, 250);
window.addEventListener('resize', handleResize);
Code language: JavaScript (javascript)
The function above will only fire once every 250 milliseconds instead of as quickly as it’s triggered; an incredible performance boost in some cases.
Thanks, you save me 🙂