Ronny vdb
Ronny vdb

Reputation: 2474

Javascript on window resize end

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

Upvotes: 19

Views: 36338

Answers (3)

Sajjad Shirazi
Sajjad Shirazi

Reputation: 2800

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

Upvotes: 0

Anas
Anas

Reputation: 1513

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

Upvotes: 21

Jonas Wilms
Jonas Wilms

Reputation: 138267

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

Upvotes: 55

Related Questions