Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic delay on jquery .click function

I have the most basic jquery function of them all, but I couldn't find a way in the documentation to trigger the contents of this click function after say 1500 milliseconds:

$('.masonryRecall').click(function(){
  $('#mainContent').masonry();
 });

P.S. just noticed the .delay function jquery 1.4, although, I am using version 1.3. I don't know whether updating this would interfere with any of the other javascript I currently have.

like image 916
kalpaitch Avatar asked Mar 30 '10 22:03

kalpaitch


People also ask

What is delay function in jQuery?

jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.

How do you add a delay to a function?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

How do I call a function after 2 seconds in jQuery?

To call a jQuery function after a certain delay, use the siteTimeout() method. Here, jQuery fadeOut() function is called after some seconds.

How do I delay onclick event?

No, but your function can set a timer event for whatever delay you want to handle it later.


2 Answers

You can do it with regular javascript using setTimeout().

$('.masonryRecall').click(function(){
        setTimeout("$('#mainContent').masonry()", 1500);
    });
like image 132
Byron Whitlock Avatar answered Sep 20 '22 23:09

Byron Whitlock


You should generally stay away from string literals in setTimeout/setInterval. Instead use a closure:

setTimeout(function(){ $('#mainContent').masonry(); }, 1500);`

and even better use it like this (note: the outer closure isn't really necessary):

(function($){
    var timeout=null;
    $('.masonryRecall').click(function(){
        clearTimeout(timeout);
        timeout=setTimeout(function(){$('#mainContent').masonry();}, 1500);
    });
}(jQuery));
like image 21
David Murdoch Avatar answered Sep 18 '22 23:09

David Murdoch