Javascript on window resize end
17,802
Solution 1
You could set a Timeout and reset it when resize is fired again. So the last timeout isnt canceled and the function is run:
function debounce(func){
var timer;
return function(event){
if(timer) clearTimeout(timer);
timer = setTimeout(func,100,event);
};
}
Usable like this:
window.addEventListener("resize",debounce(function(e){
alert("end of resizing");
}));
Solution 2
I like Jonas Wilms nifty little debounce function, however I think it would be nicer to pass the debounce time as a param.
// Debounce
function debounce(func, time){
var time = time || 100; // 100 by default if no param
var timer;
return function(event){
if(timer) clearTimeout(timer);
timer = setTimeout(func, time, event);
};
}
// Function with stuff to execute
function resizeContent() {
// Do loads of stuff once window has resized
console.log('resized');
}
// Eventlistener
window.addEventListener("resize", debounce( resizeContent, 150 ));
Author by
Ronny vdb
He who asks a question is a fool for a few minutes... he who does not ask a question remains a fool his whole life. #SOreadytohelp
Updated on June 01, 2022Comments
-
Ronny vdb almost 2 years
I am calling a function when the window is resized like this:
window.addEventListener("resize", calculateDimensions());
But I need a way to call a different function AFTER the window has been resized. Is there any way to achieve this using native js (not jquery)
TIA
-
Jonas Wilms over 6 yearsWhile this is true, its not answering the question. This would be rather a comment...
-
Ronny vdb over 6 yearsSorry if I was unclear, but I want to call the calculateDimensions as the window resizes, and a different function once the resize has ended, how would I use your great example to achieve this? Thanks!
-
Jonas Wilms over 6 years@ronny vdb you already have a calculate dimensions listener. Add the upper code, Put that other function instead of the alert above and youre done...
-
Varun almost 4 yearsI know, the op already has his answer, but for future references, I would like to add a code pen - codepen.io/dcorb/pen/XXPjpd Source - css-tricks.com/debouncing-throttling-explained-examples
-
ACJ over 2 yearsAgreed, and those first two lines could be rewritten as
function debounce(func, time = 100){
.