delay JQuery effects

83,623

Solution 1

setTimeout(function() { $('#foo').fadeOut(); }, 5000);

The 5000 is five seconds in milliseconds.

Solution 2

I use this pause plugin I just wrote

$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};

Call it like this :

$("#mainImage").pause(5000).fadeOut();

Note: you don't need a callback.


Edit: You should now use the jQuery 1.4. built in delay() method. I haven't checked but I assume its more 'clever' than my plugin.

Solution 3

Previously you would do something like this

$('#foo').animate({opacity: 1},1000).fadeOut('slow');

The first animate isn't doing anything since you already have opacity 1 on the element, but it would pause for the amount of time.

In jQuery 1.4, they have built this into the framework so you don't have to use the hack like above.

$('#foo').delay(1000).fadeOut('slow');

The functionality is the same as the original jQuery.delay() plugin http://www.evanbot.com/article/jquery-delay-plugin/4

Solution 4

You can avoid using setTimeout by using the fadeTo() method, and setting a 5 second delay on that.

$("#hideAfterFiveSeconds").click(function(){
  $(this).fadeTo(5000,1,function(){
    $(this).fadeOut("slow");
  });
});
Share:
83,623
Dónal
Author by

Dónal

I earn a living by editing text files. I can be contacted at: [email protected] You can find out about all the different kinds of text files I've edited at: My StackOverflow Careers profile

Updated on July 09, 2022

Comments

  • Dónal
    Dónal almost 2 years

    I want to fade out an element and all its child elements after a delay of a few seconds. but I haven't found a way to specify that an effect should start after a specified time delay.

  • Chris Marasti-Georg
    Chris Marasti-Georg over 15 years
    Note that this is using Javascript's built-in setTimeout function, nothing jQuery specific.
  • Jason Bunting
    Jason Bunting over 15 years
    This only partially answers his question, I think.
  • redsquare
    redsquare over 15 years
    doing this kind of block is very cpu intensive compared to setTimeout. I don't see the advantage. - Why is avoiding the native timer necessary?
  • Tormod
    Tormod about 15 years
    This helps me so much! Thank you :-)
  • aruno
    aruno about 15 years
    just watch out if jQuery ever adds a pause() function because there's will probably be better than mine! but its good to abstract away what youre doing like this
  • aruno
    aruno almost 15 years
    can someone explain WHY i dont need a callback? i'm not quite sure why this doesnt return immediately
  • gnarf
    gnarf over 14 years
    jQuery has a built in animation queue... if you never reset/stop the queue, the "pause" acts as period of animation that doesn't actually animate anything.
  • yonran
    yonran over 13 years
    stop() doesn't work with delay(), so I still use your dummy animation hack. (bug bugs.jquery.com/ticket/6576 )