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
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;
});
You can make use of jQuery one() method as shown here
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.
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.
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);
}
});
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);
};
};