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

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

    There is a much simpler method to execute a function at the end of the resize than calculate the delta time between two calls, simply do it like this :

    var resizeId;
    $(window).resize(function() {
        clearTimeout(resizeId);
        resizeId = setTimeout(resizedEnded, 500);
    });
    
    function resizedEnded(){
        ...
    }
    

    And the equivalent for Angular2 :

    private resizeId;
    @HostListener('window:resize', ['$event'])
    onResized(event: Event) {
      clearTimeout(this.resizeId);
      this.resizeId = setTimeout(() => {
        // Your callback method here.
      }, 500);
    }
    

    For the angular method, use the () => { } notation in the setTimeout to preserve the scope, otherwise you will not be able to make any function calls or use this.

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

    Here is VERY simple script to trigger both a 'resizestart' and 'resizeend' event on the window object.

    There is no need to muck around with dates and times.

    The d variable represents the number of milliseconds between resize events before triggering the resize end event, you can play with this to change how sensitive the end event is.

    To listen to these events all you need to do is:

    resizestart: $(window).on('resizestart', function(event){console.log('Resize Start!');});

    resizeend: $(window).on('resizeend', function(event){console.log('Resize End!');});

    (function ($) {
        var d = 250, t = null, e = null, h, r = false;
    
        h = function () {
            r = false;
            $(window).trigger('resizeend', e);
        };
    
        $(window).on('resize', function (event) {
            e = event || e;
            clearTimeout(t);
    
            if (!r) {
                $(window).trigger('resizestart', e);
                r = true;
            }
    
            t = setTimeout(h, d);
        });
    }(jQuery));
    
    0 讨论(0)
  • 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/

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

    One solution is extend jQuery with a function, e.g.: resized

    $.fn.resized = function (callback, timeout) {
        $(this).resize(function () {
            var $this = $(this);
            if ($this.data('resizeTimeout')) {
                clearTimeout($this.data('resizeTimeout'));
            }
            $this.data('resizeTimeout', setTimeout(callback, timeout));
        });
    };
    

    Sample usage:

    $(window).resized(myHandler, 300);

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

    i wrote a litte wrapper function on my own...

    onResize  =   function(fn) {
        if(!fn || typeof fn != 'function')
            return 0;
    
        var args    = Array.prototype.slice.call(arguments, 1);
    
        onResize.fnArr    = onResize.fnArr || [];
        onResize.fnArr.push([fn, args]);
    
        onResize.loop   = function() {
            $.each(onResize.fnArr, function(index, fnWithArgs) {
                fnWithArgs[0].apply(undefined, fnWithArgs[1]);
            });
        };
    
        $(window).on('resize', function(e) {
            window.clearTimeout(onResize.timeout);
            onResize.timeout    = window.setTimeout("onResize.loop();", 300);
        });
    };
    

    Here is the usage:

    var testFn  = function(arg1, arg2) {
        console.log('[testFn] arg1: '+arg1);
        console.log('[testFn] arg2: '+arg2);
    };
    
    // document ready
    $(function() {
        onResize(testFn, 'argument1', 'argument2');
    });
    
    0 讨论(0)
  • 2020-11-22 10:25
    var resizeTimer;
    $( window ).resize(function() {
        if(resizeTimer){
            clearTimeout(resizeTimer);
        }
        resizeTimer = setTimeout(function() {
            //your code here
            resizeTimer = null;
            }, 200);
        });
    

    This worked for what I was trying to do in chrome. This won't fire the callback until 200ms after last resize event.

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