Friday, November 7, 2008

Delay before action in jQuery

(pk)blog highlights a very easy way to simulate a delay before an action in jQuery.

Because setTimeout doesn't work in jQuery (at least not without some messing around) and there isn't a built-in delay() function (shame), the simplest method is to create the illusion of a delay by calling an action that doesn't have any visible effect.

For example, if you want a confirmation message to fade out after a certain number of seconds, you could use the following jQuery:

$('#message').fadeTo(4000, 1).fadeOut(2000);

The fadeTo method has no visible effect on the message box because its visibility is already 100%. However, the browser will still wait, giving the effect of delaying the fadeOut action by 4 seconds.

A neat little trick.