Skip to main content
Participant
August 22, 2014
Question

How do i add a countdown timer in as3 that starts when the program begins?

  • August 22, 2014
  • 3 replies
  • 1702 views

I also want it to remove everything that is on the stage when it reaches 0 and produce a Game Over screen.

This topic has been closed for replies.

3 replies

Inspiring
August 25, 2014

import flash.events.TimerEvent;

import flash.utils.Timer;

var countdown:Timer = new Timer (1000,TARGET_TIME);

//after 60 Seconds every DisplayObject will be removed from stage

const TARGET_TIME:int = 60;

countdown.addEventListener(TimerEvent.TIMER, tick);

countdown.addEventListener(TimerEvent.TIMER_COMPLETE, gameOver);

function tick(e:TimerEvent):void {

    //this will count upwards 1.2.3.4....

    trace(e.currentTarget.currentCount);

}

function gameOver(e:TimerEvent):void {

    // this function will remove all DisplayObjects from your Stage

    // starting from the top

    //It will not remove shapes or anything the user might have drawn on the stage

    //just things that are accessible to ActionScript (Sprites, MovieClips)

    for (var i:int = this.numChildren-1 ; i >= 0; i--) {

        removeChildAt(i);

    }

}

//countdown will start only if you call it explicitly

countdown.start();

Inspiring
August 25, 2014

You can do as Ned said and use a Timer or you do a simple compare between your apps start time and the current time. For example:

var startTime:Number = new Date().valueOf();

and then any time you want to see the elpased time:

var elapsed:Number = new Date().value() - startTime;

This will give you the elapsed time in milliseconds - divide by 1000 to get seconds.

Ned Murphy
Legend
August 23, 2014

One way would be to use a Timer and have it tick off based on whatever time increments you wish to display and when it completes the repeat count needed to reach the timeout you have it take care of removing whatever content you intend.  If you have no idea where to start with this either look up the Timer class in the help documents or find a Timer tutorial using Google.