Another little class... Timer

This is another class that I have to use for work, never really thought about posting it, but it’s another extremely boring day for me…

This class is really basic, and is not meant to be used with setInterval or anything, it’s more of a StopWatch… you can start, stop and reset. When you ask for the time, you ask for it in a specific format. What you do with the timer is your call, this isn’t made for anything specifically…

/* A simple timer class.. does exactly as you would expect a stop watch to do, nothing more, nothing less.
 *
 * @author Michael Avila
 * @version 1.0
 */
class XTimer
{
    private var mseconds:Number = 0; // the total milliseconds
    private var isRunning:Boolean = false; // is the timer running
    private var last_check:Number = 0; // last timer value
    
    /* The format for Milliseconds */
    public static var MILLISECONDS:Number = 1;
    /* The format for Seconds */
    public static var SECONDS:Number;
    /* The format for Minutes */
    public static var MINUTES:Number;
    /* The format for Hours */
    public static var HOURS:Number;
    
    
    public function XTimer()
    {
        SECONDS = XTimer.MILLISECONDS * 1000;
        MINUTES = XTimer.SECONDS * 60;
        HOURS = XTimer.MINUTES * 60;
    }
    
    /* Starts the timer */
    public function start():Void
    {
        isRunning = true;
    }
    /* Stops the timer */
    public function stop():Void
    {
        isRunning = false;
        last_check = getTimer();
    }
    /* Resets the timer */
    public function reset():Void
    {
        mseconds = 0;
        last_check = 0;
    }
    
    /* Returns the time, in the format you specify.
     *
     * @param The format that you wish the time to be returned in, pass in one of XTimer's properties for formats.
     * 
     * @usage <pre>myTimer.getTime(XTimer.SECONDS);</pre>
     */
    public function getTime( time_format:Number ):Number
    {
        updateTime();
        return Math.floor(mseconds/time_format);
    }
    
    // updates the timer
    private function updateTime():Void
    {
        if (isRunning)
        {
            mseconds += getTimer() - last_check;
            last_check = getTimer()
        }
    }
}

Code usage in the fla…


Key.addListener(this);

var stop_watch = new XTimer();
stop_watch.start();

function showTime()
{
    trace("Milliseconds: " + stop_watch.getTime(XTimer.MILLISECONDS));
    trace("Seconds: " + stop_watch.getTime(XTimer.SECONDS));
    trace("Minutes: " + stop_watch.getTime(XTimer.MINUTES));
}

function onKeyDown()
{
    if (Key.getCode() == Key.SPACE)
    {
        showTime();
    }
}

Enjoy, I’m curious to see what people end up using this for. Take Care.

_Michael