Creating timers using the Timer class
In previous examples, we saw how to use the setInterval() and setTimeout() methods to create simple timers.
The following example shows how you can execute code at regular intervals using the Timer class. It also shows you how you can create timers that repeat continuously as well as timers which only execute a specific number of times.
Full code after the jump.
The following example shows a very simple timer which runs continuously every 1000 ms (1 second):
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/20/creating-timers-using-the-timer-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
private var timer:Timer;
private function init():void {
timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, timer_timer);
timer.start();
}
private function timer_timer(evt:TimerEvent):void {
var tmr:Timer = evt.currentTarget as Timer;
var obj:Object = new Object();
obj.currentCount = tmr.currentCount;
obj.delay = tmr.delay;
obj.repeatCount = tmr.repeatCount;
obj.running = tmr.running;
arrColl.addItemAt(obj, 0);
}
]]>
</mx:Script>
<mx:ArrayCollection id="arrColl" />
<mx:DataGrid id="dataGrid"
dataProvider="{arrColl}"
width="100%"
rowCount="10"
verticalGridLines="false"
verticalScrollPolicy="on">
<mx:columns>
<mx:DataGridColumn dataField="currentCount" />
<mx:DataGridColumn dataField="repeatCount" />
<mx:DataGridColumn dataField="delay" />
<mx:DataGridColumn dataField="running" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
View source is enabled in the following example.
The following example shows a timer which runs exactly 5 times, and then dispatches a timerComplete event:
<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/20/creating-timers-using-the-timer-class/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
verticalAlign="middle"
backgroundColor="white"
creationComplete="init();">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
private var timer:Timer;
private function init():void {
timer = new Timer(1000, 5);
timer.addEventListener(TimerEvent.TIMER, timer_timer);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timer_timerComplete);
timer.start();
}
private function timer_timer(evt:TimerEvent):void {
var tmr:Timer = evt.currentTarget as Timer;
var obj:Object = new Object();
obj.currentCount = tmr.currentCount;
obj.delay = tmr.delay;
obj.repeatCount = tmr.repeatCount;
obj.running = tmr.running;
arrColl.addItemAt(obj, 0);
}
private function timer_timerComplete(evt:TimerEvent):void {
var tmr:Timer = evt.currentTarget as Timer;
Alert.show(tmr.currentCount + " of " + tmr.repeatCount, "Timer complete");
// Call the Timer instance's timer event handler.
timer_timer(evt);
}
private function resetTimer():void {
arrColl = new ArrayCollection([]);
timer.reset();
timer.start();
}
]]>
</mx:Script>
<mx:ArrayCollection id="arrColl" />
<mx:ApplicationControlBar dock="true">
<mx:Button label="Reset" click="resetTimer();" />
</mx:ApplicationControlBar>
<mx:DataGrid id="dataGrid"
dataProvider="{arrColl}"
width="100%"
rowCount="10"
verticalGridLines="false"
verticalScrollPolicy="on">
<mx:columns>
<mx:DataGridColumn dataField="currentCount" />
<mx:DataGridColumn dataField="repeatCount" />
<mx:DataGridColumn dataField="delay" />
<mx:DataGridColumn dataField="running" />
</mx:columns>
</mx:DataGrid>
</mx:Application>
View source is enabled in the following example.
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.
9 Responses to Creating timers using the Timer class
Leave a Reply Cancel reply
-
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


peter
happy 元宵节(sweet dumplings made of glutinous rice flour, chinese festival).
thanks for your all examples, they are very good. And i can learn a lot in your website
best wishes to you. :)
dormouse
Dear Peterd,
First, let me thank you with all my heart for your great blog! it really helps me a lot, and makes my programming in flex become a joyful experience. :)
I have a question about the memory usage of the Timer control. When i create
a time with the following code snippet, i can see the total memory used by the
flay payer going up and up, steadily, at the speed of 30K~10K per second.
what’s wrong? did i make something wrong or it is a bug of flex?
thx in advance.
regards
Galahady
p.s:
private var timer:Timer; private function init():void { timer = new Timer(1000); timer.addEventListener(TimerEvent.TIMER, timer_timer); timer.start(); } private function timer_timer(evt:TimerEvent):void { lblTotalMemory.text = String(System.totalMemory); }Galahady,
Unfortunately I cannot reproduce the issue.
Using the following code my total memory jumped from 5152768 to 5169152, where it stayed fairly steady:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init();"> <mx:Script> <![CDATA[ private var timer:Timer; private function init():void { timer = new Timer(1000); timer.addEventListener(TimerEvent.TIMER, timer_timer); timer.start(); } private function timer_timer(evt:TimerEvent):void { lblTotalMemory.text = new Date().toTimeString() + ": " + String(System.totalMemory); } ]]> </mx:Script> <mx:Label id="lblTotalMemory" /> </mx:Application>I’m not 100% certain if the
totalMemoryproperty returns the amount of memory (in bytes) used by the *current* Flash Player instance for the specific Flex application, or if it returns the amount of memory used by *all current* Flash Player instances. Meaning, your numbers may not be what you expect if you have other Flash Player instances running in the background which may be doing animations or calculations or serving advertisements or whatever.Peter
Dear Peterd,
Thx for your prompt response!
This time i’m not prudent engough. You are right. It’s not the timer’s fault, although i can reproduce the same issue again and again.
After several experiments, i guess the totalMemory might be the total amount of memory used by all Flash Player instances in the current browser process.
Thx again~!
Yours sincerely, Galahady.
@Peter,
I managed to fix my previous problems with an IFrame – you know me well!
Because i use transitions between states i needed a timer to wait and fire a complete event once the transition had completed, which is based on time also. Peter this example was very easy to modify and works perfectly.
You are the man Peter, thanks for saving us newbies and getting us there quicker.
Faith restored.
hello, I have a timer, most do not understand much of AS3, I would like to create with an external file .as to please if someone wants to help me would be very grateful.
meumaiil@hotmail.com
hi,
i using below :
private function createTimer(): void
{
var intTimeTick:Number = 0;
intTimeTick = CConst.intPriceWorldTime;
tmrRefresh1 = new Timer(intTimeTick);
tmrRefresh1.addEventListener(TimerEvent.TIMER, tmrRefresh_OnTimer);
tmrRefresh1.start();
}
private function tmrRefresh_OnTimer(event:TimerEvent): void
{
intTimmer = 0;
BindData(CCommonData.curInvestorTemp);
}
public static function BindData(curInv:Number):void
{
var objTotalInfoAccountController:CTotalInfoAccountController=new CTotalInfoAccountController();
objTotalInfoAccountController.ListTotalInfoAccount(curInv,CCommonController.ConvertDate(CCommonData.curDay.toDateString()),1,1,new mx.rpc.Responder(Result,CCommonController.faultHandler));
}
This funtion will allway request after CConst.intPriceWorldTime = 3000. But program is very slow. What is solution for this problem ?.
Thanks Peter, this is a great intro to timers!
Hi all,
I need something like that, but much more like a scheduler that executes every second.
Its a game, with a loop that must execute every second. It must execute at same time, independently of machine’s resources (cpu/memory). Its possible in flex?
Thanks,
Francisco