How to add a delay to a jQuery animation

January 15th, 2010 at 3:41 pm No Comments

A couple of days ago, I was looking for a way to add a pause after an animation was triggered. This was before jQuery 1.4 was released. I found a couple of solutions including using the javascript function setTimeout or some people would imitate a delay by setting an animation for the desired number of seconds that doesn’t change anything. Something like this…


$("#box1").fadeTo(1000, 0).fadeTo(3000, 0).fadeTo(1000, 1);

This will fade out an element in 1 second, then it will “pause” by setting another animation for 3 seconds that doesn’t change anything, then it will change it back to 100% opacity. It’s kind of an awkward way to do it.

But now with jQuery 1.4, things are a lot easier. You just need to just need to use the delay() function. Like so…


$("#box2").fadeTo(1000, 0).delay(3000).fadeTo(1000, 1);

Click on the box and notice there is a 3 second delay after the box fades out, before it reappears. Visually, the effect looks exactly the same before the delay() function was introduced, but the code is nicer now.


To set the delay before an animation fires, do this…


$("#box3").delay(3000).fadeTo(1000, .1);

Now there will be a 3 second delay before the box fades:


Or if you want to set the delay after an animation fires. Like a delay before your next lines of code are fired, do something like this… (I’m not sure if this is the best way, but it’ll work.)


$("#box4").fadeTo(1000, .1).delay(3000).fadeTo(1, .1);

And that’s all there is too it. To read more about the delay() function, check out the jQuery documentation.

Leave a Comment