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

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

提交回复
热议问题