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

后端 未结 24 1471
深忆病人
深忆病人 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:21

    You can use setTimeout() and clearTimeout() in conjunction with jQuery.data:

    $(window).resize(function() {
        clearTimeout($.data(this, 'resizeTimer'));
        $.data(this, 'resizeTimer', setTimeout(function() {
            //do something
            alert("Haven't resized in 200ms!");
        }, 200));
    });
    

    Update

    I wrote an extension to enhance jQuery's default on (& bind)-event-handler. It attaches an event handler function for one or more events to the selected elements if the event was not triggered for a given interval. This is useful if you want to fire a callback only after a delay, like the resize event, or else. https://github.com/yckart/jquery.unevent.js

    ;(function ($) {
        var methods = { on: $.fn.on, bind: $.fn.bind };
        $.each(methods, function(k){
            $.fn[k] = function () {
                var args = [].slice.call(arguments),
                    delay = args.pop(),
                    fn = args.pop(),
                    timer;
    
                args.push(function () {
                    var self = this,
                        arg = arguments;
                    clearTimeout(timer);
                    timer = setTimeout(function(){
                        fn.apply(self, [].slice.call(arg));
                    }, delay);
                });
    
                return methods[k].apply(this, isNaN(delay) ? arguments : args);
            };
        });
    }(jQuery));
    

    Use it like any other on or bind-event handler, except that you can pass an extra parameter as a last:

    $(window).on('resize', function(e) {
        console.log(e.type + '-event was 200ms not triggered');
    }, 200);
    

    http://jsfiddle.net/ARTsinn/EqqHx/

提交回复
热议问题