How to prevent calling of en event handler twice on fast clicks?

前端 未结 9 1021
小鲜肉
小鲜肉 2020-12-15 19:23

There is a button and when user clicks on button, some data is saved to back-end. Issue is when user clicks on button very quickly, event handler is getting executed multipl

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 20:21

    There are multiple ways of dealing with this:

    You can disable/hide the button after the click:

    $('#button').attr("disabled", true);
    

    You can also set a timeout on each click to ensure it does not execute again:

    var x, y = 1;
    
    $('#button').click(function() {
      if (x) clearTimeout(x);
      x = setTimeout(function() {
         // do the work here
         y++;
         console.log(y);
         // ----------------
      }, 1000);
    });
    

    So each time the button is clicked, it will only actually execute the code after a 1000 milliseconds, if the button is clicked in rapid succession, the timeout will just be cleared and start over again.

    note that the above is untested

    Personally I think the disabled solution is the best as it indicates to the user that he has clicked and something is happening, you can even show a loader next to the button as well.

提交回复
热议问题