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

房东的猫 提交于 2019-11-30 11:30:14

David Walsh has a great solution.

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

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.

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);

You can make use of jQuery one() method as shown here

I'm using the simple solution below and its been working for me well :

var x = 1;
e.handled=false;
$('#button').click(function(e) {
  if(e.handled==false){
      e.handled=true;
      // Do something
      // Save some data on network
      x++;
      console.log(x);      
  }
});
Ishank

You are looking for this

$( "button" ).one( "click", function(evt) {
  x++;
  console.log(x);
});

Or if u need a certain time interval to lapse between two effective clicks.

var last, diff;
$( "button" ).click(function( event ) {
  if (last){
    diff = event.timeStamp - last;
    if (diff >= SOMEVAL){
      x++;
      console.log(x);    
    }
  }
  last = event.timeStamp;          
});

var btn = document.querySelector('#twofuns');
btn.addEventListener('click',method1);
btn.addEventListener('click',method2);
function method2(){
  console.log("Method 2");
}
setTimeout(function(){
  btn.removeEventListener('click',method1);
},5000);
function method1(){
  console.log("Method 1");
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Pramod Kharade-RemoveEventListener after Interval</title>
</head>
<body>
<button id="twofuns">Click Me!</button>
</body>
</html>

You can remove one listener among multiple in java-script like above.

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);

});

Assuming you attached and event listener to the button, one approach ist to just remove the event listener from the button and attach it afterwards again if needed.
In the event listener function itself add the following code:

function handleButtonClick(e){
  e.target.removeEventListener("click", handleBackButton);
}

Depending on your setup this could work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!