Skovy
Skovy

Reputation: 173

jQuery button click only every 2 seconds

I am having troubles with some jQuery code when I click a button very quickly. So to solve this I need to only allow users to click a button every 2 seconds or so. How can I make a button only clickable every 2 seconds (or whatever time I choose)?

Upvotes: 5

Views: 5625

Answers (3)

jackwanders
jackwanders

Reputation: 16050

Assuming you're using <button> or <input>,

$('#yourButton').click(function(){
    var btn = $(this);
    btn.prop('disabled',true);
    window.setTimeout(function(){ 
        btn.prop('disabled',false);
    },2000);
});

jsFiddle DEMO

The 2000 is the length of time before the button is re-enabled, in milliseconds

Upvotes: 13

lc.
lc.

Reputation: 116528

Disable the button on click, and run a timer with a 2-second timeout which re-enables the button when it expires.

Upvotes: 1

Pointy
Pointy

Reputation: 413976

Have the "click" handler add a class ("clicked" maybe) to the button, and also start a timer to remove the class 2 seconds later. If the handler sees that "clicked" is already applied to the button, it does nothing.

You could also disable the button; that might be better, as it'd give the user visual indication that the button won't do anything.

Upvotes: 1

Related Questions