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

前端 未结 9 1019
小鲜肉
小鲜肉 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:16

    Try the following code

    var x = 1;
    var fewSeconds=10; /*10 seconds*/
    
    $('#button').click(function() {
    $('#button').attr("disabled", "disabled");
      x++;
      console.log(x);
        var btn = $(this);
        btn.prop('disabled', true);
        setTimeout(function(){
            btn.prop('disabled', false);
        }, fewSeconds*1000);
    
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 20:21

    As per edit

    You should use .one()

    or

    You can unbind event on click function

    var x = 1;
    function myButtonClick() {
    
        $('#button').unbind('click');
    
        // Do something
        // Save some data on network
        x++;
        console.log(x);
        $('#button').bind('click', myButtonClick);
    }
    
    $('#button').bind('click', myButtonClick);
    
    0 讨论(0)
提交回复
热议问题