jQuery: Delay execution of any function

If you ever wanted to use jQuery’s delay function to delay the execution of any other function than e.g. jQuery’s effect functions you probably tried something like this:

$(document).ready(function(){
  $("#myElement").delay(2000).trigger("click");
});

My intension was to trigger the “click” event on #myElement two seconds after the DOM was loaded. During testing however it turned out that the event was triggered right away without any delay.

Taking a closer look at the delay function showed me that only functions that are queued in jQuery’s default “fx” queue are delayed by a delay-call like the one above. If you want to delay e.g. the trigger function you either need to queue it in the fx-queue or in a separate queue. Here is how that works:

$("#myElement").delay(2000).queue(function(){ 
  $(this).trigger("click"); 
  $(this).dequeue(); 
});

If you don’t want to use the default fx-queue, this is how to queue the function in your own queue:

$("#myElement").delay(2000, "myQueue").queue("myQueue", function(){ 
  $(this).trigger("click"); 
}).dequeue("myQueue");
DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
This entry was posted in jQuery. Bookmark the permalink.

7 Responses to jQuery: Delay execution of any function

  1. David says:


    This just helped me fix my code – thank you!

  2. Santosh Subba says:


    I was pulling my hair… thanks a lot!

  3. Pingback: jQuery delaying execution and looping. | Paratrooper Digital

  4. shaon says:


    thanks, helped a lot.

  5. James says:


    Nice one, thank you :-)

  6. Tyler V. says:


    Some might find this plugin helpful. Delayed events with full support for delegation: http://www.theloveofcode.com/jquery/delayed/

  7. jitender says:


    its working…….i am thankful to you…

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>