Here’s a very tiny jQuery plugin which makes it possible to delay a jQuery animation (or any function) for any amount of time. When you call one animation after another jQuery automatically queues them up and then executes them in order. This plugin inserts a pseudo-animation into that queue resulting in what seems like a delay.

This post has been updated since it’s original publication.

The Code:

$. fn . delay = function ( time , callback ) { // Empty function: jQuery. fx . step . delay = function ( ) { } ; // Return meaningless animation, (will be added to queue) return this . animate ( { delay : 1 } , time , callback ) ; }

Usage:

$ ( 'div' ) . delay ( 1000 ) . animate ( { height : 200 } ) . delay ( 1000 ) . animate ( { height : 400 } ) . delay ( 500 ) . fadeOut ( ) . delay ( 500 ) . fadeIn ( ) ;

If you want to delay something which is not an animation then you have to pass it in it’s own function as the second parameter to ‘delay’. You can use the ‘this’ keyword to reference the current subject of the chain within this callback function:

// Change background color of all anchors after 1 second: $ ( 'a' ) . delay ( 1000 , function ( ) { $ ( this ) . css ( { background : 'red' } ) ; } ) ;

All the plugin does is fake an animation of a property which doesn’t exist. Assigning an empty function to that property isn’t necessary – it’s only for cleanliness (plus I have a feeling it won’t work in really old browsers without it).

There is a ‘delay’ plugin already made available by Evan Byrne over here, the only problem with it is that it won’t work in the same fashion as above (queuing animations) and it does not make the subject of the chain available through the ‘this’ keyword in the callback (you might argue that this is a feature though). If you don’t want normal delayed actions (adding a callback which changes some CSS, for example) to be appended to the animation queue I suggest using Evan’s.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!