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

后端 未结 24 1585
深忆病人
深忆病人 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条回答
  •  闹比i
    闹比i (楼主)
    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");
    
                }
    

    }

提交回复
热议问题