19

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

4
  • You may wanna pass a function and not the result of a function? Commented Aug 27, 2017 at 12:55
  • Use window.addEventListener("resize", calculateDimensions); calculateDimensions() means that you execute the function and then use that result as a callback function. Commented Aug 27, 2017 at 12:59
  • Check this out Commented Aug 27, 2017 at 13:00
  • related: stackoverflow.com/q/5489946 Commented Mar 17, 2023 at 10:27

3 Answers 3

56

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");
}));
Sign up to request clarification or add additional context in comments.

3 Comments

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!
@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...
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
21

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 ));

1 Comment

Agreed, and those first two lines could be rewritten as function debounce(func, time = 100){.
-1

Using npm debounce package:

npm i debounce
const debounce = require('debounce');
window.onresize = debounce(resize, 200);

function resize(e) {
  console.log('height', window.innerHeight);
  console.log('width', window.innerWidth);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.