, , , , , , ,

Recently I had cause to need a Countdown Timer in ActionScript 3, and when a certain condition was met, the need to be able to use the current time showing as a determining factor in what the next action was to be. If the countdown had reached zero, one action was required, but if there was still time on the countdown, a different action was required.

To do this, I used the basic timer code as follows:
(I needed to delay the start of the timer briefly, hence the 1 second delay timer)

// starting count of visible timer, refers to number of times the timer repeats before stopping
var timeOne:uint = 80;
var oneTimer:Timer = new Timer(1000,timeOne);

// set delay timer of 1 second before actual timer starts
var delayOneCount:Number = 1;
var delayOneTimer:Timer = new Timer(1000,delayOneCount);
delayOneTimer.addEventListener(TimerEvent.TIMER, realOneTimer);

function realOneTimer(event:TimerEvent):void
// Creates new timer with instance name of oneTimer
// Event listener for the timer
// countdownTimerOne is the function being called
oneTimer.addEventListener(TimerEvent.TIMER, countdownTimerOne);
// start the timer;

// define the countdownTimerOne function;
function countdownTimerOne(event:TimerEvent):void
oneTimer_txt.text = String((timeOne)-oneTimer.currentCount);

When the condition was met that required a choice of actions depending on the timer’s current value, I used the following code:

// test if timer has reached 0 by checking the currentCount value
if (oneTimer.currentCount == 80)

80 in this code line refers directly to the timeOne variable set at the start. This allowed me to test for the completion of the timer in a very simple manner that negated the need to reset variables.