Search code examples
actionscript-3timer

AS3 - How to fire an event precisely in time (framerate independent) like: every 1 or 5 milliseconds


I wonder if it's possible to fire an event independently of flash framerate. Tried timer class, setTimeout - setInterval and so.. but these strongly depends on frames.

For example this:

var a = 0;
var timer:Timer = new Timer(5);
timer.start();

timer.addEventListener(TimerEvent.TIMER, valAdd)

function valAdd(e:TimerEvent)
{
    a++;
}

acts similar to Event.ENTER_FRAME.. as I checked variable "a" after a second I got around 118-120 running at 60fps, not 200 as expected (timer every 5ms) So I'm looking for a solution for this. Thank you in advance for any advices regarding my little issue.


Solution

  • From Timer manual:

    Depending on the SWF file's framerate or the runtime environment (available memory and other factors), the runtime may dispatch events at slightly offset intervals. For example, if a SWF file is set to play at 10 frames per second (fps), which is 100 millisecond intervals, but your timer is set to fire an event at 80 milliseconds, the event will be dispatched close to the 100 millisecond interval. Memory-intensive scripts may also offset the events.

    This means you can never create a timer which will work on such small precision, e.g. 5 millisecond. 5 millisecond is a very small time and the run time system itself does lots of works under the hood. These timers are never that much precise.

    You need to re-design your solution which does not require a timer of such small interval.

    This timer precision problem is not present only in AS3 or flash. Timers of other languages, run times (e.g. NSTimer of iOS) also don't work with such small interval.