Harnassing the Power of Timers in AS3
Anyone who has had the experience of trying to time events for web via client side scripting before can readily appreciate the power and ease of using the robust Timer class in Actionscript 3. Similar to the idea of using JavaScript’s setTimout and/or setInterval methods, we can use this class to set a timer for a millisecond count that will simply trigger a TimerEvent when the timer has reached its end. The beauty of it, though, is that when the timer is created, we can explicitly declare how many times we want the timer to run! No more sloppy looping of intervals or timeouts: just set your timer to X number of loops and start it running.
So, obviously, if we create a timer to run once, it is the equivalent of running a setTimeout function. As with the aforementioned JavaScript functions, we set the timer with a number of milliseconds we want to wait before triggering its event. As an optional second argument, we pass in the number of cycles we wish the timer to run. Also, since the timer is an object, even if we set the timer to run only once, we can call the start method on it and manually run that single timer multiple times throughout our script. With a little creative thinking, I’m sure you can already come up with dozens of ways this could be useful.
For a small example today, I decided to come up with a simple fireworks display. The list of uses of timers in something as simple as launching a single firework is pretty impressive:
- Time between launches
- Launch path: how long to gain altitude
- Explosion fuse: how long to delay between the end of climb and explosion
- Particle burn length: how long to burn at full brightness before fading out
Of course, these could all be handled manually, but since we’re studying timers here, I wanted to show a few different uses for them. When you review the source code, I’m sure you will very quickly see how useful setting individual timers and handlers for them can be. Instead of boring you further with my rhetoric on timers, here is the sample and source code for it. Feel free to send any comments or questions.
Garth Henson has been working professionally as a web developer for nearly 10 years. When not coding in PHP, JavaScript or Actionscript, he can usually be found trying to refine his photography skills.





