Internet / Software Applications

Macromedia Flash MX 2004 ActionScript Programming Tutorial

Using the setInterval() Function

setInterval() can be used to call another function at the interval you specify. It also calls the function repeatedly until you clear it, so there’s no need for a loop—setInterval() does everything we need.

To make this work, we need to place our code for duplicating the movie clip into a function—this is the function setInterval() will call. We need to delete the while loop. We’ll place our new function in the first frame of the main timeline and call it “makeAsteroid”:

To use setInterval(), we assign it to a variable that functions as the Interval ID. The Interval ID will allow us to clear the interval later. This is the code we’ll use:

asteroidInterval = setInterval(makeAsteroid, 1000 );

The setInterval() function calls the function we created, makeAsteroid(). But it calls it at an interval of once every second. setInterval() uses intervals in milliseconds, so the value 1000 is equal to 1 second. Each time it calls makeAsteroid(), the asteroid_mc movie clip will be duplicated, making an asteroid appear on stage.

We could place this line of code in our button’s event handler, but we’re going to create a new function to keep it in instead. This allows us to call setInterval() from anywhere in the movie, while keeping the actual code for it in one place. In the first frame of the main timeline, add the following new function:

function getAsteroids() {

asteroidInterval = setInterval(makeAsteroid, 1000);

}

We placed it above our makeAsteroid() function, just to stay organized:

Next, we need to provide a mechanism to clear the interval. If we don’t, it will continue to call the makeAsteroid() function indefinitely, raining asteroids down on our ship. We use the clearInterval() function to do this, inserting our Interval ID, asteroidInterval, between the parentheses:

clearInterval(asteroidInterval);

We need to wait until 10 asteroids have been produced, though, so we can use an if statement to test whether or not num_clips equals 10, and if so, call clearInterval(). We’ll put this at the end of our makeAsteroid() function. This way, when num_clips reaches 10, which will happen inside the makeAsteroid() function, a tenth movie clip will be created, and then clearInterval() will be called:

All that’s left to do now is to call our getAsteroids() function from the play button’s event handler:

Save and test the movie. When you click the play button, 10 asteroids should come toward the ship at 1-second intervals.