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

后端 未结 24 1448
深忆病人
深忆病人 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: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);
    });
    

提交回复
热议问题