Creating a simple timer in Flex with the flash.utils.Timer class
Here’s an example of a simple timer which displays minutes, seconds, and milliseconds, which I built in Flex using the flash.utils.Timer class. You can start and stop the timer using two Button controls.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/14/creating-a-simple-timer-in-flex-with-the-flashutilstimer-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.utils.Timer;
import flash.events.TimerEvent;
private const MIN_MASK:String = "00";
private const SEC_MASK:String = "00";
private const MS_MASK:String = "000";
private const TIMER_INTERVAL:int = 10;
private var baseTimer:int;
private var t:Timer;
private function init():void {
t = new Timer(TIMER_INTERVAL);
t.addEventListener(TimerEvent.TIMER, updateTimer);
}
private function updateTimer(evt:TimerEvent):void {
var d:Date = new Date(getTimer() - baseTimer);
var min:String = (MIN_MASK + d.minutes).substr(-MIN_MASK.length);
var sec:String = (SEC_MASK + d.seconds).substr(-SEC_MASK.length);
var ms:String = (MS_MASK + d.milliseconds).substr(-MS_MASK.length);
counter.text = String(min + ":" + sec + "." + ms);
}
private function startTimer():void {
baseTimer = getTimer();
t.start();
}
private function stopTimer():void {
t.stop();
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:Button label="Start timer" click="startTimer()" />
<mx:Button label="Stop timer" click="stopTimer()" />
</mx:ApplicationControlBar>
<mx:Label id="counter" fontSize="96" />
</mx:Application>
View source is enabled in the following example.
Here’s a similar version using the DateFormatter class. Note that unlike the previous code, this version doesn’t include milliseconds in the output.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init()">
<mx:Script>
<![CDATA[
import flash.utils.Timer;
import flash.events.TimerEvent;
private const TIMER_INTERVAL:int = 10;
private var baseTimer:int;
private var t:Timer;
private function init():void {
t = new Timer(TIMER_INTERVAL);
t.addEventListener(TimerEvent.TIMER, updateTimer);
}
private function updateTimer(evt:TimerEvent):void {
var d:Date = new Date(getTimer() - baseTimer);
counter.text = dateFormatter.format(d);
}
private function startTimer():void {
baseTimer = getTimer();
t.start();
}
private function stopTimer():void {
t.stop();
}
]]>
</mx:Script>
<mx:DateFormatter id="dateFormatter" formatString="NN:SS" />
<mx:ApplicationControlBar dock="true">
<mx:Button label="Start timer" click="startTimer()" />
<mx:Button label="Stop timer" click="stopTimer()" />
</mx:ApplicationControlBar>
<mx:Label id="counter" fontSize="96" />
</mx:Application>
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
34 Responses to Creating a simple timer in Flex with the flash.utils.Timer class
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


Hey Peter, why didn’t you use binding on the textfield with a dateformatter instead of splitting up the string? I haven’t checked but does a dateformatter allow for seconds?
Just curious. Great blog btw!
John,
DateFormatter does support seconds, but I don’t believe it supports milliseconds. But yes, I probably should update the post above and show the easier/better way that uses DateFormatter as it’d be significantly less code and a better approach if you didnt need millisecond accuracy.
Hi Peter,
If I were to run this app using Adobe AIR as a windows application, what changes should be made?
Many Thanks
Benson Daniel
Hello Peter,
I use your second example, but when I use a dateformatter like JJ:NN:SS, it always starts with 01:00:00 . Is this normal? Because my getTimer is just a few seconds…. Is this a known problem? Or do you know how I have to start with 00:00:00.
Thanks a lot! And euhm… very useful blog!!!
Wannes,
What about something like this:
private function updateTimer(evt:TimerEvent):void { var ms:Number = getTimer() - baseTimer var d:Date = new Date(0, 0, 0, 0, 0, 0, ms); counter.text = dateFormatter.format(d); }Peter
Thanks Peter!
Peter,
Great Blog finding it a great help learning flex and actionscript. I was wonder if you could use the above method to display the system time on an appliction so the current user can see the date and the time? Or is there another method for that?
Thanks
David
Managed to get what I was looking for with this below. It works for what I’m looking for. Not sure if its correct. Thanks for the start.
import flash.utils.Timer; import flash.events.TimerEvent; private const TIMER_INTERVAL:int = 10; private var appTime:Timer; private function startClock():void { appTime = new Timer(TIMER_INTERVAL); appTime.addEventListener(TimerEvent.TIMER, updateTimer); appTime.start(); } private function updateTimer(event:TimerEvent):void { var currentDate:Date = new Date(); dateAndTimeDisplay.text = timeDisplayFormatter.format(currentDate); }Cheers
David
How would you add hours to this?? I attempted it but my hours started out at 18:00:00?
Nicole
I’m having the same problem with hours .. with 3900 (seconds) input as duration into the following function, it yields 19:05 instead of the expected 01:05:
private function getDuration(obj:Object, column:DataGridColumn): String { var duration: int = Objective(obj).lm ? Objective(obj).lm.video.duration*1000 : 100; var durationFormatter: DateFormatter = new DateFormatter(); durationFormatter.formatString = "JJ:NN"; return durationFormatter.format(new Date(duration)); }Figured it out: Date produces a local time, so the displayed time must be adjusted with the offset. Beware that
getTimeZoneOffset()does appear to account for daylight savings time; where newDate(0).getTimeZoneOffset()returns 360,Date().getTimeZoneOffset()returns 300 as I’m now in Central Daylight Time.private function getDuration(obj:Object, column:DataGridColumn): String { var tzOffset: int = new Date(0).getTimezoneOffset() * 60 * 1000; var duration: int = Objective(obj).lm ? Objective(obj).lm.video.duration*1000 : 100; var durationFormatter: DateFormatter = new DateFormatter(); durationFormatter.formatString = "JJ:NN"; return durationFormatter.format(new Date(duration + tzOffset)); }Thank you again for your posts, VERY helpful. I was utterly confused until I found that getTimer was in flash.utils – could not figure out by reading where that function came from!
===>
1137: Incorrect number of arguments. Expected no more than 0.
huy,
Which version of the Flex SDK, Flash Player, and OS are you using?
I’ve never seen that error before. It may be worth filing a bug at http://bugs.adobe.com/flashplayer/ .
Peter
(PS: If you post the bug number here, a few of us can vote/subscribe.)
Absolutely a super post for a beginner in Flex such as myself.
I have been able to get the sample working without any issues and am now changing it to suit my needs.
Many thanks!
Did someone has this example with pause and resume?
I tried with the same code. Unfortunately i too getting the same error mentioned earlier by huy.
Any solution to it. Pls find below for details.
Error is on line : t = new Timer(TIMER_INTERVAL);
Comments : Incorrect number of arguments. Expected no more than 0.
i got this error too.
flex builder 3
@notzipo,
I just tried w/ Flex SDK 3.4 and wasn’t able to reproduce the error.
Which version of the Flex SDK/Flash Player are you using? And on which OS?
Peter
Try using the full class name in the calls. I was getting this same error and this worked to correct it:
change
var t:Timer;
to:
var t:flash.utils.Timer;
and change
t = new Timer(TIMER_INTERVAL);
to
t = new flash.utils.Timer(TIMER_INTERVAL);
I do not know the cause of the name collision, but this will get around it.
Thanks for your post. It works OK. You gave me an idea for a banner dynamic flex.
Thanks,
awesome for beginners, you should add an entry with an option to count down ;)
Thanks
Hi, thanks for the post.
For the guys asking about the pause and resume functionality, this is the code I have added to make this work.
This methods are called from the corresponding buttons in this way:
Hope this helps.
Regards
Thanks for this, plugged-right-in nicely!
sd
For those who need to add hours
You need to add another mask var
private const HRS_MASK:String = "00";
then inside the t listener keeping peterd advice i add this
var ms:Number = getTimer() - baseTimer
var d:Date = new Date(0, 0, 0, 0, 0, 0, ms);
var hrs:String = (HRS_MASK + d.hours).substr(-HRS_MASK.length);
and at the end you need to change the TIMER_INTERVAL:int from 10 to 1000
great post, well done!
Hello, nice post.
I am having proble with this sample, when i include the flash.utils.Timer, i have this erros:
1061: Call to a possibly undefined method start through a reference with static type Timer. Timer/src
1061: Call to a possibly undefined method stop through a reference with static type Timer. Timer/src
1137: Incorrect number of arguments. Expected no more than 0. Timer/src
I am using Flex 3 on Windows xp sp3, i download the sdk 4 for flex and the errors persist.
i am using the first sample of this page
Thanks
The
start()andstop()methods aren’t static methods. I’d try copy/pasting the example above into a new project and seeing if it compiles for you.Peter
Got same errors. Copypasted code from this example to Flex Builder 3 and 4 – errors still persist. Can anyone help?
Sorry, already found the solution – look here for “ed” answer. Good luck!
Sorry i am using flash player 9 and 10
nice post.i have a similar post also maybe it can help some of you guys .check it on this link http://ntaka.co.za/?p=25
Nice post. Does anyone know if there is an easy way to make it count down and start automatically?
nice post…is it possible record the time and store it in to database or array
Thanks
Hi Peter:
Any ideas about why all this can’t be done in MXML, like (suposing xmlns:utils=”flash.utils.*”)
<utils:Timer id=”myTimer” delay=”1000″ timer=”{myTimerFunction} />
That way we could use bindings for setting the delay, avoiding addEventListener on init(), etc… but the compiler keeps throwing an error: Incorrect number of arguments (1 expected). Any ideas?
Thanks in advance :)