jQuery resize event (or Javascript one) is fired when the size of the browser’s window (viewport) changes as pointed out in jQuery documentation.
Sometimes we need to execute functions which might take a while to execute or which might consume quite a few resources from the machine. For those cases we don’t usually want to execute them tens of times while the user is still re-sizing the window to reach the desired size.
For these particular cases we can use a very simple trick:
var resizeId;
$(window).resize(function() {
clearTimeout(resizeId);
resizeId = setTimeout(doneResizing, 500);
});
function doneResizing(){
//whatever we want to do
}
Code language: JavaScript (javascript)
Basically what we do in this case is adding a timeout of 500 milliseconds to call our function doneResizing
.
This counter of 500 milliseconds gets restarted with every change in the window dimensions (as we clear the timeout) so the function will only be called if the user stops resizing the window OR if the user resizes the window VERY slowly, which is very unlikely 🙂
I’m personally making use of this trick on my fullPage.js library because it does a few changes on the DOM on resize. You can see it implemented here.
In case you want to mimic the same behaviour in vanilla Javascript, here’s the equivalent:
var resizeId;
window.addEventListener('resize', function() {
clearTimeout(resizeId);
resizeId = setTimeout(doneResizing, 500);
});
function doneResizing(){
//whatever we want to do
}
Code language: JavaScript (javascript)
Here’s a working example. You can test it by opening the codepen on a new window and resizing the right frame.