In a previous example, “Creating timers using the setInterval() method”, we saw how you can create a repeating timer using the setInterval() method.

In the following example, you will see how to create and cancel non-repeating timers using the setTimeout() and clearTimeout() methods. You’ll also see how you can pass additional parameters to the setTimeout() method which will get passed along to your custom function.

As pointed out by a keen reader in the previous example, the setInterval() and setTimeout() methods are the non-preferred methods of timers. The new and improved method is to use the Timer class.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/15/creating-timers-using-the-settimeout-method/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private var alert:Alert;

            private function delayedAlert():void {
                setTimeout(launchAlert, 2000);
                button.enabled = false;
            }

            private function launchAlert():void {
                alert = Alert.show("I'm an alert.");
                button.enabled = true;
            }
        ]]>
    </mx:Script>

    <mx:Button id="button"
            label="Click here to launch alert (2 second delay)"
            click="delayedAlert();" />

</mx:Application>

View source is enabled in the following example.

In the following example, we see how to use the clearTimeout() method to cancel the timer. Note how this time we save the uint value returned from the setTimeout() method. This saved value will be later passed to the clearTimeout() method.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/15/creating-timers-using-the-settimeout-method/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import flash.utils.clearTimeout;
            import mx.controls.Alert;

            private var alert:Alert;
            private var timeoutID:uint;

            private function delayedAlert():void {
                timeoutID = setTimeout(launchAlert, 2000);
                startBtn.enabled = false;
                cancelBtn.enabled = true;
            }

            private function launchAlert():void {
                alert = Alert.show("I'm an alert.");
                startBtn.enabled = true;
                cancelBtn.enabled = false;
            }

            private function cancelAlert():void {
                clearTimeout(timeoutID);
                startBtn.enabled = true;
                cancelBtn.enabled = false;
            }
        ]]>
    </mx:Script>

    <mx:Button id="startBtn"
            label="Click here to launch alert (2 second delay)"
            click="delayedAlert();" />

    <mx:Button id="cancelBtn"
            label="Cancel alert!"
            enabled="false"
            emphasized="true"
            color="red"
            themeColor="red"
            click="cancelAlert();" />

</mx:Application>

View source is enabled in the following example.

The following example shows you how you can pass additional parameters to the setTimeout() method, and how those parameters are then passed to your custom function, which in this case is the launchAlert() method. Note how the launchAlert() method takes two parameters: message (required) and title (optional; default empty string).

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/02/15/creating-timers-using-the-settimeout-method/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;

            private var alert:Alert;

            private function delayedAlert():void {
                setTimeout(launchAlert, 2000, "Alert message", "Alert title");
                button.enabled = false;
            }

            private function launchAlert(message:String, title:String = ""):void {
                alert = Alert.show(message, title);
                button.enabled = true;
            }
        ]]>
    </mx:Script>

    <mx:Button id="button"
            label="Click here to launch alert (2 second delay)"
            click="delayedAlert();" />

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

3 Responses to Creating timers using the setTimeout method

  1. Marshall says:

    Thanks very much for your great work on this blog. I’ve learned a lot!

    I’m working with code almost exactly like your second exmaple. I want to call a piece of code using the setTimeout() method. However, I’ve found an issue with how it passes parameters to the method it will call. My code is as follows:

    function foo(event:MouseEvent):void
    {
    setTimeout(myMethod,300,event);
    }

    myMethod(event:MouseEvent)
    {

    }

    The problem is, that the event object, which I am passing as a paremeter through the setTimer() method is being changed during the passing. The currentTarget is DIFFERENT for the event being set as a paremeter on setTimeout and the event being passed to myMethod by setTimeout().

    The code in MyMethod uses the event, and eventually passes it to doDrag() in the DragManager so I need my event intact.

    Any ideas about why the currentTarget property is being changed by the setTimout() call? Any way I can get around this?

  2. Thiago says:

    Hi Mashall, good one event.clone(). Solve my problems here.

    thanks

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