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

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

    Internet Explorer provides a resizeEnd event. Other browsers will trigger the resize event many times while you're resizing.

    There are other great answers here that show how to use setTimeout and the .throttle, .debounce methods from lodash and underscore, so I will mention Ben Alman's throttle-debounce jQuery plugin which accomplishes what you're after.

    Suppose you have this function that you want to trigger after a resize:

    function onResize() {
      console.log("Resize just happened!");
    };
    

    Throttle Example
    In the following example, onResize() will only be called once every 250 milliseconds during a window resize.

    $(window).resize( $.throttle( 250, onResize) );
    

    Debounce Example
    In the following example, onResize() will only be called once at the end of a window resizing action. This achieves the same result that @Mark presents in his answer.

    $(window).resize( $.debounce( 250, onResize) );
    

提交回复
热议问题