views:

51

answers:

4

Hi,

I'm using Flash CS4 with AS3. I want a timer to call a function at 50 ms intervals for 100 times. however the timer takes much longer than it should, which adds up to 1677 ms (1.677 seconds!) too much after 100 repeats. Am I missing something here or is the timer THAT inaccurate?

Code

function test(event:TimerEvent):void{
   trace("GetTimer(): " + getTimer() + " || Timer.currentCount: " + _timer.currentCount);
}

var _timer:Timer = new Timer(50, 100); 
_timer.addEventListener(TimerEvent.TIMER, test); 
_timer.start();

Trace Output:

GetTimer(): 74 || Timer.currentCount: 1

GetTimer(): 140 || Timer.currentCount: 2

GetTimer(): 209 || Timer.currentCount: 3

GetTimer(): 275 || Timer.currentCount: 4

GetTimer(): 340 || Timer.currentCount: 5

GetTimer(): 407 || Timer.currentCount: 6

GetTimer(): 476 || Timer.currentCount: 7

GetTimer(): 542 || Timer.currentCount: 8

GetTimer(): 608 || Timer.currentCount: 9

GetTimer(): 677 || Timer.currentCount: 10

......

GetTimer(): 3340 || Timer.currentCount: 50

......

GetTimer(): 6677 || Timer.currentCount: 100

Thanks for help.

Regards,

Chris

+1  A: 

A lot of factors can affect the accuracy of a Timer. The SWF frame rate, other processes, basically the general environment for your movie.

PatrickS
+7  A: 

Don't use Timer for such small intervals. Timing in Flash is not simple topic, see this to start. To measure 50 ms, I suggest getTimer() function and ENTER_FRAME event to check if time interval has passed.

alxx
getTimer() should be used very precision is important.
Muhammad Irfan
@Muhammad Irfan - getTimer() is no more precise than a Timer object.
Allan
@Allan - getTimer allows for manual callback calling, while Timer can accumulate error as the question shows.
alxx
@alxx - Yes I know (I agree with your answer), the comment though seemed to imply that getTimer() was based on a different and more accurate timer system (well thats how I read it).
Allan
A: 

if i were you i'd count an amount of milliseconds between frames (1000 / fps) and decide to call a function every certain amount of frames. is this amount is more than 1:

var counter:int = 0;
const COUNT_TO_INVOKE: int = 2;//if calling every 3 frames
function onEnterFrame(e: Event):void{
    counter++;
    if(counter == COUNT_TO_INVOKE){
        timerFunction();
        counter = 0; 
    }
}
www0z0k
Real FPS may vary under the load.
alxx
yes, and sometimes it's better to skip a function call then to continue loading the system (and enlarging frame delays)
www0z0k
A: 

Try to use auto-correcting timer something like this

http://actualwave.com/blog/?p=484
http://cookbooks.adobe.com/post_Accurate_timer-17332.html

Pavel fljōt