Javascript on window resize end

半腔热情 提交于 2020-01-13 10:43:16

问题


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


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



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



回答3:


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

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



来源:https://stackoverflow.com/questions/45905160/javascript-on-window-resize-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!