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

后端 未结 24 1221
深忆病人
深忆病人 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.

提交回复
热议问题