user1022585
user1022585

Reputation: 13641

disable jquery function for x seconds

I have an image with a jquery click attached to it

<img src=pic.gif id="action">

and some jquery

$("#action").click(function(){ 
    alert("DONE");
    }); 

How could I edit this so that the action function can't run for x seconds after it has ran? Say if I wanted it disabled for 5 seconds after each click.

Upvotes: 1

Views: 3063

Answers (2)

Sushanth --
Sushanth --

Reputation: 55740

You can store the function in a variable. In that unbind the event and again attach it. This makes sure it will run only after the time period elapses..

Try this

var click = function() {
    $("#action").click(function() {
        alert("DONE");
        // Unbind the event
        $('#action').unbind();
        // Call the function after 2 second delay
        setTimeout(function() {
            click();
        }, 2000);
    });
    };
click();
​

Check this DEMO

Upvotes: 3

Kyle
Kyle

Reputation: 22258

This is just an example, you may want to look into Namespaced Events to prevent unbinding all click handlers.

var action_click = function(){
  var $self = $(this);

  alert("done"); // do your thing

  $self.unbind('click'); // unbind the click handler

  // rebind the handler after 5 second delay
  setTimeout(function(){
    $self.click(action_click);
  }, 5000);

};

// setup initial click handler
$('#action').click(action_click);

Example Fiddle

Upvotes: 0

Related Questions