17

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

Ronny vdb
  • 2,324
  • 5
  • 32
  • 74

4 Answers4

50

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");
}));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    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 Aug 27 '17 at 13:06
  • @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... – Jonas Wilms Aug 27 '17 at 13:07
  • I know, the op already has his answer, but for future references, I would like to add a code pen - https://codepen.io/dcorb/pen/XXPjpd Source - https://css-tricks.com/debouncing-throttling-explained-examples/ – Varun May 19 '20 at 06:12
17

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 ));
Anas
  • 1,345
  • 14
  • 15
  • Agreed, and those first two lines could be rewritten as `function debounce(func, time = 100){`. – ACJ Dec 09 '21 at 13:25
0

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);
}
Sajjad Shirazi
  • 2,657
  • 26
  • 24
-4

Use window.addEventListener("resize", calculateDimensions);

calculateDimensions() means that you execute the function and then use that result as a callback function.

Michael Schmidt
  • 110
  • 1
  • 14