When resize() in JQuery, trigger fires multiple times

前端 未结 2 1773
独厮守ぢ
独厮守ぢ 2021-01-17 03:38

I use Paul Irish Smartresize but when I resize the window the function inside resize() fires multiple times causing my accordion not to work properly. Does anyone have any i

2条回答
  •  一生所求
    2021-01-17 04:15

    That happens because when you are re-sizing, the re-size event fires multiple times. Teorically(more for illustration purposes) when the JavaScript loop goes through the verification of the window size it detects it is smaller/larger than before and fires it again. As the loop is very fast you get multiple fires, during your "single" re-size.

    You can do something like this:

    var idCounter = 0;
    $(window).smartresize(function(){
      var myId=(++idCounter);
      setTimeout(function(){
        if(myId===idCounter){
           anim3();
        }
      }, 500); // 500 milli the user most likely wont even notice it
    }
    

    This should safely ignore the multiple fires and only process on the last one. (Unless you take lots of time to resize, in that case you can increase the timeout)

提交回复
热议问题