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 ));
Share:
17,802
Ronny vdb
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, 2022

Comments

  • Ronny vdb
    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
    Jonas Wilms over 6 years
    While this is true, its not answering the question. This would be rather a comment...
  • Ronny vdb
    Ronny vdb over 6 years
    Sorry 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
    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
    Varun almost 4 years
    I 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
    ACJ over 2 years
    Agreed, and those first two lines could be rewritten as function debounce(func, time = 100){.