Flex Timer Example
Line Break
Author: Arjan (34 Articles) - Author Website
Arjan is a SAP Consultant specialized in ABAP and Front End development techniques like Web Dynpro, Adobe Interactive Forms, Flex and AIR. In his free time he likes to create examples for Flex-Blog and other applications using Flex, AIR and PHP. Other hobbies are movies and music. He is also the co-owner of Flex-Blog.com.
Let’s say you want something to happen in your application every once in a while automatically. The Timer class is the way to do it. I was already familiar with the Timer class from C#, the Flex one isn’t all that different. Let’s create a simple exmple, just switching an image every XX seconds.
First, set up your layout, we only need an image, declare it using MXML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <mx:Image width="1024" height="768"/> </code> Now we need some variable to store the current image URL in, make it a private var in your script section: [cc lang="actionscript"] <mx:Script> <![CDATA[ [Bindable] private var currentImageUrl:String = "http://www.flex-blog.com/samples/sample12/image1.jpg"; ]]> </mx:Script> |
Ok, with that done we need that Timer to that we talked about, let’s create an initialize method that creates a Timer with a delay of five seconds (5000 milliseconds) and starts the timer:
1 2 3 4 5 6 7 | private function init():void{ var timer:Timer = new Timer(5000); timer.addEventListener(TimerEvent.TIMER, switchImage); timer.start(); } |
Add it to the initialize event in the application tag:
1 2 3 | <mx:Application initialize="init()" xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> |
Notice that I added an event listener to the timer variable before starting it. This event listener is called every time the Timer reaches five seconds, let’s implement the event listener:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private function switchImage(event:TimerEvent):void{ if(currentImageUrl == "http://www.flex-blog.com/samples/sample12/image1.jpg") { currentImageUrl = "http://www.flex-blog.com/samples/sample12/image2.jpg"; } else { currentImageUrl = "http://www.flex-blog.com/samples/sample12/image1.jpg"; } } |
This example is simple, it just checks whether the current image is image1 and switches it to image2 if it is. If it isn’t, the current image must be image2 so image1 has to be shown.
So now you have a basic understanding of the Timer class, it’s very useful sometimes!
View the complete source by using right-click -> view source.
Related posts:
- Flex 4 Effect Example: Sliding text using the Move Effect
- Progressbar in Datagrid Example
- Image as Button in a DataGrid


(