11

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.

Dustin Laine
  • 37,935
  • 10
  • 86
  • 125
kalpaitch
  • 5,193
  • 10
  • 43
  • 67

2 Answers2

17

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

$('.masonryRecall').click(function(){
        setTimeout("$('#mainContent').masonry()", 1500);
    });
Byron Whitlock
  • 52,691
  • 28
  • 123
  • 168
  • @Bryon Whitlock Thanks for that. Just to add its .masonry(). But also the timeout doesn't seem to be working. it still fires immediately??? – kalpaitch Mar 30 '10 at 23:06
  • Again thanks for the direction. just another minor alteration and it works perfectly: setTimeout("$('#mainContent').masonry()", 1500); – kalpaitch Mar 30 '10 at 23:12
  • 2
    Don't use quotes around the function. That's equivalent to using eval(). You should instead wrap it in an anonymous function, or use [jQuery's proxy function](http://stackoverflow.com/questions/20221163/way-to-execute-jquery-member-functions-inside-settimeout-without-closure). – Alex W Feb 03 '14 at 21:38
16

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));
David Murdoch
  • 87,823
  • 39
  • 148
  • 191