topical media & game development

talk show tell print

student-mma-16-MyTimer.ax

student-mma-16-MyTimer.ax [swf] flex


  package
  {
          import flash.events.TimerEvent;
          import flash.utils.Timer;
          
          
A timer for interval timing, which compensates for timing inaccuracy on the next loop. If a timer is x miliseconds late, the next interval will be called x miliseconds earlier.

  
          public class @ax-student-mma-16-MyTimer
          {
                  private var time:Number;
                  private var timer:Timer;
                  private var timerFunction:Function;
                  private var repeatCount:int;
                  private var delay:Number;
                  
                  public function @ax-student-mma-16-MyTimer(delay:Number, repeatCount:int, timerFunction:Function)
                  {
                          timer = new Timer(delay, 1);
                          timer.addEventListener(TimerEvent.TIMER, interval);
                          this.timerFunction = timerFunction;
                          if(repeatCount == 0) repeatCount = -1;
                          this.repeatCount = repeatCount;
                          this.delay = delay;
                  }
                  
                  public function start():void {
                          time = new Date().time;
                          timer.start();
                  }
                  
                  public function stop():void {
                          timer.stop();
                  }
                  
                  private function interval(e:TimerEvent):void {
                          timerFunction();
                          repeatCount--;
                          if(repeatCount == 0) return;
                          var now:Number = new Date().time;
                          var timeElapsed:int = now - time;
                          var overtime:int = timeElapsed - delay;
                          time = now - overtime;
                          timer = new Timer(delay - overtime, 1);
                          timer.addEventListener(TimerEvent.TIMER, interval);
                          timer.start();
                  }
  
          }
  }
  


(C) Æliens 04/09/2009

You may not copy or print any of this material without explicit permission of the author or the publisher. In case of other copyright issues, contact the author.