Creating Timers in Flash, Part 2
Two more ways to skin the same cat
Timing stuff in Flash isn't exactly the glitziest of tasks, but sometimes it just has to be done. In our last installment, we went over two relatively basic methods for creating timers, each with varying degrees of simplicity and/or accuracy. Today we're going for as much accuracy as we can, and we're going in two completely opposite directions. Intriguing? I thought so. I am, after all, the master of suspense, so let's get down to business, shall we?
Method 3: setInterval
Yes, we are at Method 3. No, we haven't jumped ahead; Methods 1 and 2 were outlined in our previous installment, which is available here. So now that you're all caught up, let's forge ahead. The setInterval method is similar to the getTimer() method we went through last time, in that it "exists" outside any frame-based activity you may have going on in your movie. It's also potentially even more accurate than the getTimer() method, because it doesn't rely on how fast a single frame runs inside of your movie in order to operate. Now, to the lay person (or, in this case, the Flash designer who may not be intimately familiar with ActionScript), setInterval can appear to be one strange-looking piece of code. It almost works backwards from the way you'd expect it to, as it sets up and references code first that you haven't even written. Lost yet? No worries—here's the example, and then we'll walk through it.
01 | var interval:Number = 5;
02 | function someCodeToRun() {
03 | clearInterval(mySetInterval);
04 | trace(interval+" seconds have elapsed");
05 | }
06 | mySetInterval = setInterval(this, "someCodeToRun", interval*1000);
Since I just got through saying how backwards this method may seem, I might as well back that up by explaining Line 6 first. Line 6 is the "meat" of the code, since it's where you actually set the interval in the setInterval function. So, let's break it down. First, here's Line 6 once again in its entirety:
mySetInterval = setInterval(this, "someCodeToRun", interval*1000);
- mySetInterval If I've said it once, I've said it a thousand times: things really get moving in Flash once you assign a name to something. That's certainly true in this case, where we've turned the code that follows into a variable by giving it a name; in this case, naming it mySetInterval will allow us to refer to it as such later on. I mean earlier on. Sorry—that whole backwards code thing. Bear with me; it will all make sense soon enough.
- setInterval() This is the "parent" function, so there's not too much extra explanation needed here. All the good stuff is happening inside the parentheses anyway.
- this This (or, in this case, this) simply sets the target for the setInterval function to watch. We haven't done anything fancy that would require targeting any other object (like place a Movie Clip instance on the Stage or anything), so chances are that you won't need to change this very much.
- "someCodeToRun" This is a custom function that will be called when the setInterval period has passed. You can sneak a peek at the code in Lines 2-5 to see what this function does, but that would be cheating, wouldn't it?
- interval*1000 The length of the interval. Why isn't this just a number? If you remember from last time, I introduced the habit of defining the desired interval (in seconds) as a variable (shown on Line 1 here), so you can easily change the number of seconds you want the timer to count off. But what's with the ol' asterisk-one-thousand garbage? Well, like getTimer(), the setInterval function operates on milliseconds, so I'm just performing a bit of math there, multiplying the 5 second interval (again, defined in Line 1) by 1000 to convert it to milliseconds.
So far, so good, right? Now, since we're working backwards, let's go over the custom someCodeToRun function. Remember, this is the code that gets called when the interval has elapsed, so, like all of the other methods we've discussed so far, we're just going to write a trace that tells us that time's up (fig. 1):

Figure 1
That explains Line 4, but what's going on with Line 3? Here it is again:
clearInterval(mySetInterval);
The clearInterval call is pretty simple. If it's present, and the name of your variable is contained in its cute little parentheses, it will effectively erase your interval. If you don't use clearInterval, the interval that you've set will just reset and start counting again, which itself is a useful feature in certain situations. So if you want to time something once, make sure to clear the interval using clearInterval in your custom function. If you want a repeating interval, don't clear the interval.
So that's pretty much that. One lingering question, though: why do we have to write the custom function first that clears the interval that isn't written until later? The answer is that a function has to be defined before you can call it. It doesn't matter that you're calling a variable name that hasn't been read first—just because you've written a function doesn't mean you've run it yet, so it's "inactive" code. You "activate" it by calling it in the body of the setInterval function on Line 6. If you were to rearrange things and move Line 6 up to Line 2, for example, you'd get an error because you're calling a function that hasn't been defined yet.
One last thing before we move on. The setInterval method is arguably the most accurate way of measuring time in Flash, because the frame rate of the movie is not a factor at all. Setting an interval tells Flash to start counting regardless of the frame rate, so even if your movie is set to 1 frame per second, you won't have to worry about an enterFrame function or (heavens forfend) a "physical" play head in the Timeline messing things up. Still with me here? Good. We still have one more method yet to discuss, one that wasn't really meant to be used to measure time but does the job just as well (and very accurately to boot). Pray tell, what is it?
Method 4: getting sneaky with the Tween Class
Not too terribly long ago, I wrote another 2-parter on Flash's Tween Class and all the fun you can have with it. Without rehashing the content contained in those articles, the Tween Class allows you to take animation out of the realm of keyframing and into the world of scripting. The Tween Class is incredibly useful once you decide to dive into interactive animation, but we're going to do something a little different with it. Considering the subject of this piece, you can probably see what that direction might be. First, though, since I'm not going to go into the Tween Class in great detail here today, I suggest you check out the articles on the Tween Class. Part 1 is available by clicking here, and you can get to part 2 by clicking here. The "Yay! Code!" heading of Part 1 will be especially useful here, since there's a complete breakdown of the various parts of the Tween Class syntax. I'm patient; I'll wait here until you get back.
Now that you've got a handle on the basics of the Tween Class, we're going to pare things down a bit, since what we're really after is the built-in duration setting. Without further ado, here's the adapted code:
01 | var interval:Number = 5;
02 | myTween = new mx.transitions.Tween(null, "_alpha", mx.transitions.easing.None.easeNone, 0, 0, interval, true);
03 | myTween.onMotionFinished = function() {
04 | trace(interval+" seconds have elapsed");
05 | };
Let's break it down a bit. You should all recognize Line 1 by now; it's the variable for the number of seconds that has shown up in the other three methods. Line 2 is the base Tween Class call, complete with a name (myTween) that ultimately lets it be monitored by the code in Lines 3-5. Notice also on Line 2 that we've abstracted a few items. For one, instead of targeting a specific Movie Clip instance, we're targeting null; literally, we're not targeting anything. This is because we're not actually interested in Tweening anything; remember, we're after the duration setting only. Now, it doesn't really matter which property we choose here, as again, we're not setting a real target. So whether we decide to rotate nothing or set the alpha for nothing (as we've done in this example), it's still nothing. It also makes no difference which Easing Class (None) or Easing Method (easeNone) you ultimately use, but just out of habit, I typically use the None options to keep things cleaner. What does matter is that the interval is set to the number of seconds you want (in this case, the interval variable of 5 that we defined in Line 1). It's also important that the last argument is always true, since as we learned in the articles on the Tween Class, true tells the Tween Class to interpret the number you specify as seconds and false tells the Tween class to interpret the number as frames.
Moving on to what's happening in Lines 3-5, we're using one of the event handlers of the Tween Class (onMotionFinished) to "sniff" for when the fake Tween we've constructed is done, which then triggers our familiar trace action on Line 4. If you test the movie and wait five seconds you'll see the Output window pop up with (yes, once again) what we saw twice in part 1 and once already here: our familiar, oh-so-exciting Figure 1.

Figure 1: Again, for the fourth time
The only question that remains here is why would you even use the Tween class as a timing device when so many other methods are available? Well, other than the fact that more options are rarely a bad thing (at least when it comes to Flash), if you're a heavy Tween Class user anyway, sometimes it smooths the process to have your method of timing use the same code as your method of animating certain sequences. In other words, in the heat of the moment, you won't have to "break stride" to implement another solution in the midst of what sometimes may be a gazillion other Tweens. Add in the fact that the Tween Class can also operate outside of the host movie's frame rate, which makes it a pretty accurate method of measuring time, and using the Tween Class as a timing device can make a lot of sense in various situations.
Well folks, there you have it. Four methods, all to accomplish the same thing. Exciting stuff? Not at all—let's not kid ourselves here. But being able to keep track of time in Flash has a million and one uses, so it's a solid skill to have under your belt.
Got Feedback? to send an email. I'll do my best to answer. Really.
