jQuery: delay and intervals of animations

jQuery (as of version 1.4) provides the delay() method to allow web developers to create a certain delay between animations and effects. This method accepts as its sole parameter a time value expressed in milliseconds. Its basic usage is $(element).effect1().delay(time).effect2(). This means that the execution of the second jQuery's effect is delayed by a certain time value defined in the delay() method. In this post I'm going to show you a practical example of how we can make this method work together with JavaScript intervals.

Consider the basic example of the following three-steps animation:

  1. an element fades out (1 second)
  2. it pauses (1 second)
  3. the element fades in (1 second)

The overall duration of the above animation is 3 seconds (3000 milliseconds). Each step lasts 1 second (1000 milliseconds). We also want the animation to enter in an infinite loop. Here's how we can do using delay() and intervals:

$('#run').click(function(e) {
    window.setTimeout(function() {
      window.setTimeout(arguments.callee, 3000);
    }, 25);

The second call to setTimeout() creates the infinite loop. Note that in this second call the duration must be equal to the overall duration of the entire animation (3000 milliseconds). You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.