Delaying a click event with .delay()

Talha picture Talha · Feb 4, 2013 · Viewed 46.2k times · Source

I have a button that gets triggered by the click of another button. I want to delay click of the second button for two seconds. I used .delay() but it didn't work.

jq(function() {
      jq('a.box').click(function() {
         jq(this).closest('.button').find('.add_this').delay(2000).click();
      })
    });

or Using setTimeout;

jq(function() {
      jq('a.box').click(function() {
      setTimeout(function(){
         jq(this).closest('.button').find('.add_this').click();
      },800);
      });
    });

But didn't work.

Answer

Dakait picture Dakait · Feb 4, 2013

from the docs http://api.jquery.com/delay/

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

you can use setTimeout to bind click handler after a delay

setTimeout(function(){

jq('a.box').closest('.button').find('.add_this').click();
},2000);

EDIT

jq(function() {
      jq('a.kklike-box').click(function() {
      $this = $(this);
      setTimeout(function(){
         $this.closest('.deal_buttons').find('.add_this').click();
      },800);
      });
    });