Skip to content

Instantly share code, notes, and snippets.

@tdavies
Created June 29, 2012 08:22
Show Gist options
  • Save tdavies/3016640 to your computer and use it in GitHub Desktop.
Save tdavies/3016640 to your computer and use it in GitHub Desktop.
Fluent Timer class
/**
* User: tom
* Date: 14/05/12
* Time: 14:46
*/
package {
import org.osflash.signals.Signal;
import flash.events.TimerEvent;
import flash.utils.Timer;
public class Delay {
private var _timer:Timer;
private const _completeSignal:Signal = new Signal();
private const _tickSignal:Signal = new Signal();
public function Delay(milliseconds:int,repeatCount:int = 1,autoStart:Boolean= true) {
_timer = new Timer(milliseconds,repeatCount);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE,delayOverHandler);
_timer.addEventListener(TimerEvent.TIMER,timerTickHandler);
if(autoStart){
start();
}
}
public function start():Delay{
if(_timer){
_timer.start();
}
return this;
}
public function pause():Delay{
if(_timer){
_timer.stop();
}
return this;
}
public function stop():Delay{
if(_timer){
_timer.reset();
}
return this;
}
public function onComplete(handler:Function):Delay{
_completeSignal.add(handler);
return this;
}
public function onTick(handler:Function):Delay{
_tickSignal.add(handler);
return this;
}
public function dispose():void{
if(_timer){
_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,delayOverHandler);
_timer.removeEventListener(TimerEvent.TIMER,timerTickHandler);
_timer = null;
_completeSignal.removeAll();
_tickSignal.removeAll();
}
}
public function get count():int{
if(_timer == null) return null;
return _timer.currentCount;
}
public function get repeatCount():int{
if(_timer == null) return null;
return _timer.repeatCount;
}
private function timerTickHandler(e:TimerEvent):void {
_tickSignal.dispatch();
}
private function delayOverHandler(e:TimerEvent):void {
_completeSignal.dispatch()
dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment