How to wait for the 'end' of 'resize' event and only then perform an action?

后端 未结 24 1190
深忆病人
深忆病人 2020-11-22 09:39

So I currently use something like:

$(window).resize(function(){resizedw();});

But this gets called many times while resizing process goes o

相关标签:
24条回答
  • 2020-11-22 10:12

    I wrote a function that passes a function when wrapped in any resize event. It uses an interval so that the resize even isn't constantly creating timeout events. This allows it to perform independently of the resize event other than a log entry that should be removed in production.

    https://github.com/UniWrighte/resizeOnEnd/blob/master/resizeOnEnd.js

            $(window).resize(function(){
                //call to resizeEnd function to execute function on resize end.
        //can be passed as function name or anonymous function
                resizeEnd(function(){
    
    
    
        });
    
            });
    
            //global variables for reference outside of interval
            var interval = null;
            var width = $(window).width();
        var numi = 0; //can be removed in production
            function resizeEnd(functionCall){
                //check for null interval
                if(!interval){
                    //set to new interval
                    interval = setInterval(function(){
            //get width to compare
                        width2 = $(window).width();
            //if stored width equals new width
                        if(width === width2){
                            //clear interval, set to null, and call passed function
                            clearInterval(interval);
                            interval = null; //precaution
                            functionCall();
    
                        }
            //set width to compare on next interval after half a second
                        width = $(window).width();
                    }, 500);
    
                }else{
                    //logging that should be removed in production
                    console.log("function call " + numi++ + " and inteval set skipped");
    
                }
    

    }

    0 讨论(0)
  • 2020-11-22 10:15

    This is what I use for delaying repeated actions, it can be called in multiple places in your code:

    function debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };
    

    Usage:

    $(window).resize(function () { 
       debounce(function() {
              //...
        }, 500);
    });
    
    0 讨论(0)
  • 2020-11-22 10:16

    There is an elegant solution using the Underscore.js So, if you are using it in your project you can do the following -

    $( window ).resize( _.debounce( resizedw, 500 ) );
    

    This should be enough :) But, If you are interested to read more on that, you can check my blog post - http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce(deadlink)

    0 讨论(0)
  • 2020-11-22 10:17

    Mark Coleman's answer is certainly far better than the selected answer, but if you want to avoid the global variable for the timeout ID (the doit variable in Mark's answer), you could do one of the following:

    (1) Use a an immediately invoked function expression (IIFE) to create a closure.

    $(window).resize((function() { // This function is immediately invoked
                                   // and returns the closure function.
        var timeoutId;
        return function() {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function() {
                timeoutId = null; // You could leave this line out.
                // Code to execute on resize goes here.
            }, 100);
        };
    })());
    

    (2) Use a property of the event handler function.

    $(window).resize(function() {
        var thisFunction = arguments.callee;
        clearTimeout(thisFunction.timeoutId);
        thisFunction.timeoutId = setTimeout(function() {
            thisFunction.timeoutId = null; // You could leave this line out.
            // Code to execute on resize goes here.
        }, 100);
    });
    
    0 讨论(0)
  • 2020-11-22 10:17

    I don't know is my code work for other but it's really do a great job for me. I got this idea by analyzing Dolan Antenucci code because his version is not work for me and I really hope it'll be helpful to someone.

    var tranStatus = false;
    $(window).resizeend(200, function(){
        $(".cat-name, .category").removeAttr("style");
        //clearTimeout(homeResize);
        $("*").one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",function(event) {
          tranStatus = true;
        });
        processResize();
    });
    
    function processResize(){
      homeResize = setInterval(function(){
        if(tranStatus===false){
            console.log("not yet");
            $("*").one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",function(event) {
                tranStatus = true;
            }); 
        }else{
            text_height();
            clearInterval(homeResize);
        }
      },200);
    }
    
    0 讨论(0)
  • 2020-11-22 10:18

    this worked for me as I did not want to use any plugins.

    $(window).resize(function() {
        var originalWindowSize = 0;
        var currentWidth = 0;
    
        var setFn = function () {
            originalWindowSize = $(window).width();
        };
    
        var checkFn = function () {
            setTimeout(function () {
                currentWidth = $(window).width();
                if (currentWidth === originalWindowSize) {
                    console.info("same? = yes") 
                    // execute code 
                } else {
                    console.info("same? = no"); 
                    // do nothing 
                }
            }, 500)
        };
        setFn();
        checkFn();
    });
    

    On window re-size invoke "setFn" which gets width of window and save as "originalWindowSize". Then invoke "checkFn" which after 500ms (or your preference) gets the current window size, and compares the original to the current, if they are not the same, then the window is still being re-sized. Don't forget to remove console messages in production, and (optional) can make "setFn" self executing.

    0 讨论(0)
提交回复
热议问题