jQuery: animations and timers

There are two types of timers in JavaScript: timers that delay the execution of an action for a certain amount of time and timers that make that action enter in an infinite loop, thus repeating the action itself over and over again. In this post I'm going to show how to implement repeated jQuery animations using the setTimeout() function of JavaScript. Bear in mind that jQuery creates a local private scope each time you use one of its methods, so to use this global function we have to use the extended syntax window.function() to make it work. Let's see a practical example.

$(document).ready(function() {


    window.setTimeout(function() {
    
        $('#test').animate({opacity: 'toggle'}, 2000);
        
        window.setTimeout(arguments.callee, 2000);
    
    
    }, 2000);
    
    window.setTimeout(function() {
    
    
        $('#test2').animate({left: 150}, 1000, function() {
            $(this).animate({left: 0}, 1000);
            
        });
        
        window.setTimeout(arguments.callee, 2000);
        
        
    
    
    }, 2000);


});

By using another setTimeout() function inside the main one and passing a reference to the main function itself as one of its arguments, we actually make the whole action enter in an infinite loop. Since the actions lasts 2000 milliseconds, we have to use consistent time references, both on setTimeout() and animate().

Note that these are two separate actions. If you want to achieve the effect of sequential infinite animations, just create a function with nested timers and then invoke that function inside setTimeout() using arguments.callee as the first argument of a second timer. Example:


function repeatAction() {

window.setTimeout(function() {

    // action 1
    
    window.setTimeout(function() {
    
    
    // action 2
    
        window.setTimeout(function() {
        
          // action 3
        
        
        }, 1000);
    
    
    }, 1000);



}, 1000);

}


window.setTimeout(function() {


   repeatAction();
   
   window.setTimeout(arguments.callee, 3000); // repeatAction() timers: 1000 + 1000 + 1000


}, 1000);

We've specified 3000 milliseconds in the second call to setTimeout() because this is the resulting sum of all the timers used in the repeatAction() function.

Demo

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.