2
votes

I have a timer counting up in as3. I am trying to simulate a clock counting up from 07:30 to 12:00. The functionality of the counting is working. How would i set an initial start value and a stop value?

Here is my code:

var timer:Timer = new Timer(100, 50);
timer.start();

timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 10;


function timerTickHandler(Event:TimerEvent):void
{
    timerCount += 10000;
    toTimeCode(timerCount);
}

function toTimeCode(milliseconds:int) : void 
{
    //creating a date object using the elapsed milliseconds
    var time:Date = new Date(milliseconds);

    //define minutes/seconds/mseconds
    var minutes:String = String(time.minutes);
    var seconds:String = String(time.seconds);
    var miliseconds:String = String(Math.round(time.milliseconds)/100);

    //add zero if neccecary, for example: 2:3.5 becomes 02:03.5
    minutes = (minutes.length != 2) ? '0'+minutes : minutes;
    seconds = (seconds.length != 2) ? '0'+seconds : seconds;

    //display elapsed time on in a textfield on stage
    timer_txt.text = minutes + ":" + seconds;

}
1

1 Answers

2
votes

There are a few ways you can do this. I'll share 2 of them.

  1. Initialize a date object to your starting time: (before your timer starts ticking)

    var time:Date = new Date();
    time.setHours(7, 30);
    

    Then append your milliseconds to the time every timer interval:

    time.time += milliseconds;
    

    This would be a good way to go if you needed to stop the clock for some reason.

  2. If you don't need to stop the clock ever (and wanted an accurate clock), you could do the following:

     var time:Date = new Date();
     time.setHours(7,30);
     var offset:Number = flash.utils.getTimer(); //this gets the amount of milliseconds elapsed since the application started;
    

    Then in your interval method:

     time.time += flash.utils.getTimer() - offset;