Recipe 14.7. Using Timers


Problem

You want to poll a method at a specific interval or add a delay.

Solution

Use the flash.util.Timer class.

Discussion

The flash.util.Timer class allows you to add timed events or a delay to method calls. You can construct a Timer instance with the constructor. Pass the constructor a number of milliseconds to use as the interval between timer events. The following example instantiates a Timer object that dispatches events every 1,000 milliseconds (1 second):

var timer:Timer = new Timer(1000);

Once you've constructed the Timer, you next need to add an event listener to handle the events it dispatches. Timer objects dispatch flash.event.TimerEvent events. The timer event is dispatched at the interval specified when constructing the Timer object (or as set by the delay property). The following example code defines an event listener for the timer event (using the TimerEvent.TIMER constant), which calls a method named onTimer( ):

timer.addEventListener(TimerEvent.TIMER, onTimer);

The event handler method is passed a TimerEvent object:

function onTimer(event:TimerEvent):void {   trace("on timer"); }

Timer objects do not start automatically; you must call the start( ) method first:

timer.start(  );

By default, timers run until stopped by the stop( ) method. However, you can also specify a number of intervals by passing a second parameter to the constructor. The default value of 0 causes the timer to repeat indefinitely, while non-zero values specify a finite number of intervals. The following constructs a timer that has just five intervals:

var timer:Timer = new Timer(1000, 5);

You can use a timer with just one interval to add a delay. The following timer code defers the call to the deferredMethod( ) method for five seconds:

var timer:Timer = new Timer(5000, 1); timer.addEventListener(TimerEvent.TIMER, deferredMethod); timer.start(  );




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net