Search code examples
javascriptjqueryloopsfadeinfadeout

How do I do 3 animations in jQuery and loop them? (Timing is messed up.)


I have a three different transitions for fading out and fading in my 3 images.

animate1 = function() {
    $('#changingImage').fadeOut('fast', function() {
        $('#changingImage').attr("src","../files/others/image1.jpg");
        $('#changingImage').fadeIn('fast');
    });
};

I have this same function two more times, just replacing the 1s with 2s and 3s. I call my three functions with this, repeating every 5 seconds:

animate1().delay(5000);
animate2().delay(10000);
animate3().delay(15000);

I'm new at jQuery, and I don't understand why the timing is wrong. All that happens is image2 (the original) gets replaced with image1, and that's it.


Solution

  • Try using the setTimeout() javascript function.

    Documentation: http://www.w3schools.com/jsref/met_win_settimeout.asp

    For example:

    setTimeout(function(){ animate1(); }, 5000);
    setTimeout(function(){ animate2(); }, 5000);
    setTimeout(function(){ animate3(); }, 5000);
    

    This basically 'pauses' your JavaScript/jQuery code for 5 seconds before running the function and continuing.