Tutorial details:
Written by: Jesse Stratford
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:

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