Skip to content

Instantly share code, notes, and snippets.

@edeustace
Created November 26, 2010 13:47
Show Gist options
  • Save edeustace/716731 to your computer and use it in GitHub Desktop.
Save edeustace/716731 to your computer and use it in GitHub Desktop.
A simple countdown class
package com.ee.example.timing
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;
[Event(type="flash.events.Event", name="countdownComplete")]
public class Countdown extends EventDispatcher
{
public static const COUNTDOWN_COMPLETE:String = "countdownComplete";
public static const COUNTDOWN_UPDATE:String = "countdownUpdate";
public static const MINUTES:int = SECONDS * 60;
public static const SECONDS:int = 1000;
public var unit:int = SECONDS;
private var _startValue:int;
private var isCounting:Boolean;
private var timer:Timer;
public function start():void
{
timer = new Timer(unit, _startValue);
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();
isCounting = true;
}
public function set startValue(value:int):void
{
if (isCounting)
{
return;
}
_startValue = Math.max(value, 1);
dispatchEvent(new Event(COUNTDOWN_UPDATE));
}
public function stop():void
{
timer.stop();
isCounting = false;
dispatchEvent(new Event(COUNTDOWN_UPDATE));
removeTimer();
}
[Bindable("countdownUpdate")]
public function get value():int
{
if (isCounting)
{
return _startValue - timer.currentCount;
}
return _startValue;
}
private function onTimer(event:TimerEvent):void
{
if (value == 0)
{
dispatchEvent(new Event(COUNTDOWN_COMPLETE));
isCounting = false;
removeTimer();
}
dispatchEvent(new Event(COUNTDOWN_UPDATE));
}
private function removeTimer():void
{
timer.removeEventListener(TimerEvent.TIMER, onTimer);
timer = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment