Search code examples
actionscript-3loopsgsap

Repeat & Reset Loop


I was wondering if it is possible to Repeat and Reset a loop. I'm using TweenLite to create a slide animation of 3 images. Each with a delay of 3 second between them.

After 6 seconds I want this loop to repeat itself so I have a slideshow. Any suggestions because so far I have ended up with endless loops causing it to crash.

var clips:Array = [image, image2, image3];
var i = 0;

while ( i < 4) {
    var timer = i;
    TweenLite.to(clips[i], 6, {x:300, ease:Linear.easeNone,delay:timer*3});
    i++;
}

Solution

  • Loops will run as fast as the program can, synchronously, locking the thread until completed. That means that anything time based, should not be in a loop (as loops have no concept of time)

    I would suggest using the complete callback built into TweenLite.

    //create a var to store which item is current
    var curIndex:int = 0;
    
    //animate the current item
    next();
    
    function next(delay:Number = 0):void {
        //when the tween is complete, call the 'tweenComplete` function and pass the curIndex as a parameter
        TweenLite.to(clips[curIndex], 2, {x: 300, ease:Linear.easeNone, onComplete: tweenComplete, onCompleteParams: [curIndex], delay: delay);
    
        //increment the current index, reset to 0 if out of range
        curIndex++;
        if(curIndex >= clips.length){
            curIndex = 0;
        }
    }
    
    function tweenComplete(index){
        next(); //animate the next item
    
        //get the previous item and reset it's x position (now that this new item is in place) 
        index--;
    
        //if index was 0, get the highest index instead
        if(index < 0) index = clips.length - 1;
    
        clips[index].x = -300; //whatever your default x value is.
    }