Understanding AS3 Timer Class

A lot of time ago I wrote about AS2 time management in Flash simple timer/countdown. Now it’s time to see how to manage time with AS3.

AS3 has its own class to manage time, the Timer class. You can read some documentation about this class in the official AS3 page, but in this test drive I am going to create two different timers… one using time intervals and one checking for elapsed time at every frame.

You will find some differences.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	public class as3timer extends Sprite {
		var interval_timer = new timetext;
		var frame_timer = new timetext;
		public function as3timer() {
			addChild(interval_timer);
			addChild(frame_timer);
			frame_timer.y = 50;
			var time_count:Timer = new Timer(1000);
			time_count.addEventListener(TimerEvent.TIMER, show_time);
			stage.addEventListener(Event.ENTER_FRAME,on_enter_frame);
			time_count.start();
		}
		function show_time(event:TimerEvent) {
			interval_timer.txt.text = event.target.currentCount;
		}
		function on_enter_frame(event:Event) {
			var elapsed = getTimer();
			frame_timer.txt.text = Math.floor(elapsed/1000)+"."+(elapsed%1000);
		}
	}
}

Let’s analyze this script:

Line 4: I need Timer class to create a Timer variable.

Line 5: I need getTimer class to use getTimer function. getTimer returns the number of milliseconds since the movie started.

Line 6: I need TimerEvent class to make a time event listener.

Lines 9-10: interval_timer and frame_timer are two dynamic text fields that will contain the number of seconds elapsed with both methods. Since I am using dynamic text fields, I had to include the TextField class at line 7.

Line 15: This is the core of the time based method. When I use new Timer(x, y);, I dispatch an event every x milliseconds for y times. If y is omitted, I dispatch an event every x milliseconds forever. In this case, I am dispatching the event every second, forever.

Line 16: This is the listener for the timer event that points to the show_time function.

Line 17: This is a simple listener for a new frame pointing on on_enter_frame function

Line 18: Starting the timer

Line 21: Updating the dynamic text field with currentCount, that stores the number of times the target has been triggered (in this case the number of seconds).

Line 25: In this case I simply get the time passed with getTimer and display it on screen.

Here it is:

At a first glance both methods work, but if you let them run for a while, you will notice they will differ more and more.

Look at this picture:

If you let timers run a lot, the difference is quite big.

What kind of timer would you use?

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers