Thursday, 22 July 2010

Stopping the timeline in Actionscript 3

In this post I will show you different scenarios of stopping the timeline in Actionscript 3. Lets suppose you want to stop the timeline in the last frame, you can simply use the stop() method in the last frame. Alternatively, if you want to keep all your code in the first frame then you can use the code below. The code uses the enter frame event to detect when the current frame on the timeline has reached the total number of frames, and stops the timeline.

//Stops at the last frame
stage.addEventListener(Event.ENTER_FRAME, stopLastFrame);

function stopLastFrame(event:Event):void{
    if(this.currentFrame == this.totalFrames){
        stop();
    }    
}

When you’re creating a banner ad, you sometimes need to stop the timeline after a certain number of iterations. The code below will stop the play head when three iterations of the timeline have played.

//Stops after three timeline iterations.
var counter:uint;

stage.addEventListener(Event.ENTER_FRAME, stopLastFrame);

function stopLastFrame(event:Event):void{
    if(this.currentFrame == this.totalFrames){
        if(counter >= 3){
            stop();
        }else{
            counter++;
        }
    }    
}

You might need to start the timeline again after a certain number of iteration, so the code below stops the timeline after three iterations then starts again after three seconds.
stage.addEventListener(Event.ENTER_FRAME, stopLastFrame);

function stopLastFrame(event:Event):void{
    if(this.currentFrame == this.totalFrames){
        if(counter >= 3){
            stop();
            setTimeout(startAgain,3000);
        }else{
            counter++;
        }
    }    
}


function startAgain():void{
    play();
}

You may wish to stop the timeline after a certain number of seconds. You can use the getTimer() method to tell when you have reached a particular time. Simply, use the code below to stop the timeline after 30 seconds. If you want to stop at a particular frame you can place the code in that frame.
if(getTimer() > 30000){
    stop();
}
This is the same code as above but you can assign the frame you want to stop at.
function stopFrameTime(_milliseconds:Number,frame:uint):void{
    if(getTimer() > _milliseconds){
        gotoAndStop(frame);
    }    
}

stopFrameTime(30000,10);

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP