ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Delaying Actions
http://www.actionscript.org/resources/articles/106/1/Delaying-Actions/Page1.html
Jesse Stratford
Jesse lives and works in Melbourne Australia. He is the Cofounder of http://ActionScript.org. A Flash enthusiast, teacher, author, freelancer and speaker Jesse's main focus nowadays is managing http://ActionScript.org, but he enjoys participating actively in community and the wider Flash scene when he has time. 
By Jesse Stratford
Published on September 9, 2005
 
Tutorial details:
Written by: Jesse Stratford [email:jessestratford@actionscript.org]
Time: 10 minutes
Difficulty Level: Intermediate
Requirements: Flash 5 and above.
Topics Covered: How to delay an action without crashing the Flash player.
Assumed knowledge: Instances, paths, Clip Events.

Page 1 of 2
Tutorial details:
Written by: Jesse Stratford [email:jessestratford@actionscript.org]
Time: 10 minutes
Difficulty Level: Intermediate
Requirements: Flash 5 and above.
Topics Covered: How to delay an action without crashing the Flash player.
Assumed knowledge: Instances, paths, Clip Events.

Enter a number less than 10 into the box below then click the Go button (love that pink!) and wait that many seconds for the stupid face to appear. If you want the source you can grab it.

This tutorial will cover how you can insert a delay of X seconds before performing an action. Those of you using Flash MX might want to take a look at my Intervals tutorial as well which outlines a nicer way of doing it in Flash MX. This question has popped up so many times in the last week that it warrants a tutorial. I don't know where people have seen it (generally this sort of thing is triggered by some great site which everyone wants to duplicate) but it's a common enough request.

Most people try to achieve this effect using some sort of scripted loop (while, for etc) and end up crashing the Flash player. Why this happens is outlined in the Scripted Loops tutorial. For now, suffice to say it's the wrong way to go about things.

It is for this reason I suggest people use ClipEvents for delaying actions. Basically the principle I employ involves setting off a counter or checker which waits until a set condition is true then runs some code. The onClipEvent (enterFrame) handler, when placed upon a movie clip on the stage will execute the actions within its scope every time Flash moves to the next frame. So if your frame rate is 12fps, the onClipEvent (enterFrame) handler executes 12 times each second. With that in mind can you anticipate how we're going to determine if a set time delay has passed?

Bing! Time's up. We can do it in one of two ways: (i) We could increment a counter using the EnterFrame handler, and then divide this number by our frame rate (let's say 12fps) to get the number of seconds elapsed, or; (ii) we can set a variable to the getTimer() value when we initiate our loop and then check if the current time is X seconds greater than that time. This second method is more dynamic and so I tend to use it over method (i). The code is something like this:

[as]onClipEvent (enterFrame) {
        if (_root.delay) {
                if (_root.waitHowLong<=(getTimer()/1000)-_root.startTime) {
                        // Time is up!
                        _root.delay = false;
                } else {
                        // Keep waiting...
                }
        }
}[/as]



Page 2 of 2
What it does (line by line):
  1. Perform these actions every time the frame changes (even if your _root level is stopped these actions will still continue to be performed 12 times a second, assuming your fps is 12).
  2. If the _root level variable delay is true;
  3. If the _root level variable waitHowLong is less than or equal to the current time in seconds minus the time at which we began counting
  4. Comment - Insert your actions on this line
  5. Set the _root level variable delay to False.
  6. Else for like 3's If
  7. Comment just for neat coding purposes
  8. Close Line 6's Else
  9. Close Line 2's If
  10. Close Line 1's Clip Event.

So you can see that, given a few variables, this code will loop until the time is right, then execute the actions on Line 4. Those variables are:

_root.delay - Boolean variable, marks if we are running a delay loop at the moment. This allows us to save on CPU usage if we are not currently running a delay, because if delay = false the rest of the actions in this code are skipped

_root.waitHowLong - A number variable (Integer or Floating point) which states the time in seconds we wish to wait before carrying out Line 4's actions

_root.startTime - Floating point variable set upon initiation of delay, see below.

Triggering:

Having now setup the engine which will control our delay we need to give it some info. This trigger info can be sent from a keyframe or a button. Let's look at a button:

[as]on (release) {
        _root.delay = true;
        _root.startTime = (getTimer()/1000);
}
[/as]

This code, placed upon a button will set the delay variable to true and thus initiate our delay loop. It also sets the startTime variable (to the current number of seconds since the movie began). So in order for this to work you also need to put this code somewhere:

[as]_root.waitHowLong = 5;
[/as]

(This makes a 5 second delay).

The best thing about this script is that it allows you to change the length of the delay dynamically, as shown here:

[as]on (release) {
        _root.waitHowLong = random(10)+1;
        _root.delay = true;
        _root.startTime = (getTimer()/1000);
}
[/as]

This button will create a delay of a random number of seconds.

Known Limitations:

Like they say in Seinfeld, "1 Chip, 1 Dip!". If you want to run more than one concurrent delay you will need more than one controller movie clip and you will also need to create a whole new set of variables (delay2, startTime2, etc)

That's it really!

Jesse Stratford [email:jessestratford@actionscript.org] is the Co-Master of ActionScript.org and a freelance Flash developer and teacher. He is based in Australia and enjoys all things Flash.

NB: If you have comments or feedback please feel free to email me, but please do not email me Flash questions; the forums are provided for that purpose and you will get a faster answer by posting you question there.

If you have found this tutorial helpful, I hope that you will take 30 seconds to visit The Hunger Site where, with just one click you can make a free donation of food to a starving person in a third-world country. We do not benefit financially from this action; it is purely an act of charity.
This tutorial is protected by International Intellectual Property Rights laws and may not be reproduced or redistributed in full or part, without the prior written consent of the author. Unauthorized reproduction of this tutorial or its contents may result in prosecution. I've worked hard on this tutorial, please don't steal it.