20
Feb
08

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):

View MXML

<?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:

View MXML

<?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.


6 Responses to “Creating timers using the Timer class”


  1. 1 dormouse Feb 20th, 2008 at 6:00 pm

    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

  2. 2 Galahady Jun 14th, 2008 at 2:17 pm

    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);
    }
    
  3. 3 peterd Jun 14th, 2008 at 9:30 pm

    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 totalMemory property 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

  4. 4 Galahady Jun 16th, 2008 at 9:34 am

    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.

  5. 5 saul Dec 1st, 2008 at 11:25 am

    @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.

  6. 6 Douglas querubin Dec 2nd, 2008 at 1:14 pm

    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

Leave a Reply

This blog is terrible at eating HTML tags. If you plan on posting code/XML, please escape your "<" characters as "&lt;" and your ">" characters as "&gt;".




February 2008
M T W T F S S
« Jan   Mar »
 123
45678910
11121314151617
18192021222324
2526272829  

Badge Farm

  • Firefox 2
  • Powered by Redoable 1.2
  • Feeds burnt by Feedburner
  • Feed