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.

 
Tagged with:
 
About The Author

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.

9 Responses to Creating timers using the Timer class

  1. dormouse says:

    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. Galahady says:

    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. peterd says:

    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. Galahady says:

    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. saul says:

    @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. Douglas querubin says:

    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

  7. thuyhh says:

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

  8. Andre says:

    Thanks Peter, this is a great intro to timers!

  9. Francisco says:

    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

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree