When resize() in JQuery, trigger fires multiple times

前端 未结 2 1766
独厮守ぢ
独厮守ぢ 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 03:56

    Here's a great piece of code that handles this for you :

    http://benalman.com/projects/jquery-throttle-debounce-plugin/

    Also see:

    http://benalman.com/projects/jquery-dotimeout-plugin/

    0 讨论(0)
  • 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)

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