Javascript on window resize end

前端 未结 3 520
谎友^
谎友^ 2021-01-12 03:05

I am calling a function when the window is resized like this:

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

But I need a way

3条回答
  •  感动是毒
    2021-01-12 03:28

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

提交回复
热议问题