flash.utils.Timer depends on flash framerate and when running its delay is changing and you can’t expect exact delay that you defined.
I have extended the default Timer by aw.utils.AccurateTimer class, to prevent delay changing.
Let's start from simple example how Timer class works. This code will show us the difference between defined delay and real values:
package{
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
[SWF(frameRate="24")]
public class TestTimer extends Sprite{
protected var _started:int;
public function TestTimer():void{
super();
const timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
_started = getTimer();
timer.start();
}
protected function timerHandler(event:TimerEvent):void{
const count:int = (event.target as Timer).currentCount;
trace(count, (getTimer()-_started-1000*count)*0.001);
}
}
}
Here is an output from 27-th iteration:
27 0.79
28 0.79
29 0.791
30 0.833
31 0.835
32 0.875
33 0.918
34 0.9580000000000001
35 0.966
36 1
37 1.002
38 1.042
39 1.083
1 second difference, can you believe?
aw.utils.AccurateTimer works exactly like flash.utils.Timer class, it uses own event - AccurateTimerEvent, that extends TimerEvent, so you can change only a class names and all will work:
package{
import aw.events.AccurateTimerEvent;
import aw.utils.AccurateTimer;
import flash.display.Sprite;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
[SWF(frameRate="24")]
public class TestTimer extends Sprite{
protected var _started:int;
public function TestTimer():void{
super();
const timer:Timer = new AccurateTimer(1000);
timer.addEventListener(TimerEvent.TIMER, timerHandler);
_started = getTimer();
timer.start();
}
protected function timerHandler(event:AccurateTimerEvent):void{
const count:int = (event.target as Timer).currentCount;
trace(count, (getTimer()-_started-1000*count)*0.001);
}
}
}
With this class output will look like this:
27 0.027
28 0.025
29 0.026000000000000002
30 0.025
31 0.027
32 0.027
33 0.025
34 0.025
35 0.025
36 0.027
37 0.026000000000000002
38 0.025
39 0.027
As you can see, some difference still here, but it is not increasing.
AccurateTimer corrects itself with each iteration and some iterations will be longer, another shorter. But if application stuck on one of iterations and taken too much time, AccurateTimerEvent.missedIterations can say you how much iterations you missed.
Also, AccurateTimer has methods pause() and resume(), to pause and resume current iteration.
+