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