Using the Timer Class
by
senocular | 24 March 2011
Have questions? Discuss this Flash / ActionScript
tutorial with others on the forums.
ActionScript 3 introduces a new class to ActionScript
called the Timer class (flash.utils.Timer).
This class is kind of like a suped-up setInterval (flash.utils.setInterval())
that sends event messages out over a period of time measured
in milliseconds. Because it uses events (flash.events.TimerEvent)
and not a callback like setInterval, a single Timer instance
can be used to call many different functions as long as they
are made listeners of that instance.
Additionally, Timer gives you the ability to control how
many times it repeats, unlike setInterval which repeats
indefinitely until clearInterval is used to shut it down, as
well as the ability to start and stop the timer on command.
Here is an example:
- var
timer:Timer
= new
Timer(500,
10);
- timer.addEventListener(TimerEvent.TIMER,
notifier);
- timer.addEventListener(TimerEvent.TIMER,
stopper);
- stage.addEventListener(MouseEvent.CLICK,
continuer);
- function
notifier(event:TimerEvent):void
{
- trace(timer.currentCount);
- }
- function
stopper(event:TimerEvent):void
{
- switch
(timer.currentCount)
{
- case
5:
- timer.stop();
- break;
- case
timer.repeatCount:
- timer.reset();
- break;
- }
- }
- function
continuer(event:MouseEvent):void
{
- timer.start();
- }
- timer.start();
In this example, the timer instance sends a
TimerEvent.TIMER event every
500 milliseconds and repeats 10 times. There are 2 event
listeners responding to these events, one tracing the
current count of the timer and the other which will either
stop (on current count of 5) or reset the timer (on current
count of total count) based on the timer's current count. A
mouse click to the stage will allow you to restart the timer
as a result of it being stopped in the stopper listener.
What you end up getting is:
- 1
- 2
- 3
- 4
- 5
- (pause;
click
to continue)
- 6
- 7
- 8
- 9
- 10
- (pause;
click
to continue)
- 1
- 2
- 3
- 4
- 5
- ...
This was a
very concise explanation of what the Timer class does and
how you can use it. To see an example of how you can use the
Timer in a more common scenario, check out the
Hiding Mouse Cursor After Some Time tutorial.
If you have any questions, feel free to post them on the
forums.
|