Calling Code at Specific Intervals
Now that you have a subtle animated background, it's time to add text to the SWF file. You should already have an embedded font in your Library from a previous exercise in this chapter. This example shows you how to create text fields on the fly, trigger scripts at timed intervals, and use a new method in the Tween class: continueTo(), which allows you to continue animating an object. By using the setInterval() function, you can make Flash suspend code execution until an internal timer reaches a certain number of milliseconds (thousandths of a second).If you set an interval of 2000 milliseconds, Flash calls a specific function after roughly two seconds. It bears mentioning that it won't call the function at exactly 2000 milliseconds, but usually it calls it within a range of 20502100 millisecondsso close enough to 2000 milliseconds that it usually can't be noticed. If you want to see how accurate the setInterval() function calls your function, you can try the following code snippet in a new Flash document:
This code uses the setInterval() function to call the user-defined checkTimer() function every 2000 milliseconds (2 seconds). Next, you define the checkTimer() function and use it to trace the value of the getTimer() function, which returns the number of milliseconds that have passed because the SWF file starts playing. If you test this script in the Flash environment you'll see that a new string is displays in the Output panel roughly every two seconds.The setInterval() function takes at least two parameters: the name of a function to call, and an interval at which the function will be called. If you supply more additional parameters, pass to the specified function as arguments. For example, consider the following code:
setInterval(checkTimer, 2000);
function checkTimer():Void {
trace("cT: "+getTimer()+" ms");
}
The third parameter in the setInterval() function, the string "lorum ipsum" passes to the checkTimer() function as the argument my_str where it is traced and displayed in the Output panel roughly every 2 seconds.
setInterval(checkTimer, 2000, "lorum ipsum");
function checkTimer(my_str:String):Void {
trace(my_str);
}
Exercise 4: Clearing and setting intervals
Before you can begin animating a few sample strings, you need to add a few variables to the top of the Actions panel. You should already have an array of colors that you used earlier to change the color of the rectangles as they were added to the Stage, as well as a TextFormat object that sets the font face to the font embedded in your library.
1. Add the two following lines of code to the Actions panel below the definition of the TextFormat object:
The first variable, root_mc, stores a reference to the main Timeline of the movie clip. This is sometimes necessary when you're working with complex scripts and need to refer to the main Timeline, and you can't use the this keyword because it might not always refer to the Timeline. Although it is true that you could instead use _root to refer to the main Timeline, it wouldn't always work properly if this SWF file were loaded into another movie at runtime. (Macromedia's best practices guide also discourages the use of _root if possible.)The second variable, interval_array, will be used to hold a numeric ID returned by the setInterval() function. This ID will be used later to clear the intervals created using setInterval(). You may have noticed that calling setInterval() not only calls a function after a set number of milliseconds, but it continues to call that function until the interval is cleared using the clearInterval() function and passing an interval ID.Now that you understand how intervals work, you add some to the project to call new text fields and animate them across the Stage at specified intervals. This lets you add an element of timing to the file by using ActionScript, so users can view and read the text before it disappears off the Stage.2. Select frame 1 of the actions layer. Enter the following code snippet at the bottom of the code already in the Actions panel:
var root_mc:MovieClip = this;
var interval_array:Array = new Array();
3. Select Control > Test Movie to review the Flash document in the authoring environment. You should see each of the three strings (string one, string two, and string three) display immediately in the Output panel (Figure 7.10).
animateText("string one");
animateText("string two");
animateText("string three");
function animateText(my_str:String,
interval_index:Number):Void {
trace(my_str);
}
Figure 7.10. Three strings immediately appear in the Output panel.

5. Preview the Flash document in the authoring environment again and you should see the strings being displayed at different intervals (1 second, 2.5 seconds, and 4 seconds).Because you're now using the setInterval() function, animateText, you call the code every 1000 milliseconds and display the string "string one" in the Output panel. If you want to have the text displayed only once and then stop tracing the value, clear the interval by using the clearInterval() function and pass an interval ID. When you call the setInterval() function, the interval ID for that interval is returned by Flash, in the previous code that value is saved into the interval_array array.The setInterval() function passes two arguments to the animateText() function: a string and a numeric value that corresponds to the array index containing the current interval ID. You'll notice in the first line of code that you're assigning the interval ID to position 0 in the array and passing 0 as a parameter to the setInterval() function. This way you know the array index that contains the current interval ID.6. Modify the animateText() function so that the interval clears immediately and is called only one time. Because the second argument, interval_index, contains the array index of the interval ID, you need to add one line at the very top of the function, as shown in the following code in boldface:
interval_array[0] = setInterval(animateText, 1000,
"string one", 0);
interval_array[1] = setInterval(animateText, 2500,
"string two", 1);
interval_array[2] = setInterval(animateText, 4000,
"string three", 2);
7. Preview your code again in the Flash environment and you should see Flash trace the appropriate string after 1000, 2500, and 4000 milliseconds respectively.
function animateText(my_str:String,
interval_index:Number):Void {
clearInterval(interval_array[interval_index]);
trace(my_str);
}
Exercise 5: Creating dynamic text fields
Now that your intervals are set and cleared correctly, you can create dynamic text fields and add them to the Stage. Text fields can be created using the MovieClip class' createTextField() method, discussed near the beginning of this chapter. The createTextField() method takes six arguments: an instance name for the newly created text field, a depth to assign the text field to, X and Y coordinates, and width and height values.
1. Remove the trace statement from the animateText() function (TRace(my_str);) and replace it with the following code:
The first new line of code creates a string named instance_str, which contains the instance name for the new text field. Similar to code for attaching the rectangles in a previous exercise, the text fields will be assigned names such as string0_txt and string2_txt. This lets you target specific text instances on the Stage.The second line of code creates a new text field to the root_mc scope (root_mc is a movie clip that was created in a previous exercise and points to the main timeline of the Flash document). You assign the text field the instance name contained in the string instance_str, and the next-highest available depth in the main timeline. The final four parameters are X and Y coordinates, width, and height. These values are temporary and you modify them later on in the script.2. Next, create an alias to the current text field that will point to the newly created text field, which makes it easier to reference the text field and its properties. Add the following line of code to the animateText() function:
function animateText(my_str:String,
interval_index:Number):Void {
clearInterval(interval_array[interval_index]);
var instance_str:String =
"string"+interval_index+"_txt";
root_mc.createTextField(instance_str,
root_mc.getNextHighestDepth(), 0, 0, 100, 20);
}
Now you can refer to the new text field by using my_txt instead of having to resort to the rather inelegant root_mc[intstance_str].3. In an earlier example, you created an instance of the TextFormat class named txt_fmt that uses an embedded font. Call the TextField class' setNewTextFormat() method to apply the text format to the newly created text field by adding the following code to the animateText() function:
var my_txt:TextField = root_mc[instance_str];
Now any new text assigned to the my_txt text field use the defined font and styles.4. Add the following five lines of code to the bottom of the animateText() function:
my_txt.setNewTextFormat(txt_fmt);
This code sets the _alpha of the text field to 20%. Depending on which colors you selected, this might be too little alpha so make adjustments as necessary. Next, the text field centers vertically by setting the _y position of the text field to the height of the Stage minus the height of the text field divided by 2. If your Stage happened to be 400 pixels high, and your text field was 100 pixels high, the code would set the _y property of the text field to 150 pixels because (400100)/2 equals 150. This would leave a 150-pixel margin at both the top and bottom of the text field.You set the text field's autoSize property to true to resize the text field to fit the text. If the text field is too big, it will become smaller so it just fits the text; conversely, if there is too much text to fit in the text field, it will stretch so that all the text is visible instead of being cut off.The final line of code sets the text in the text field to the value in the my_str variable, which is the first argument in the animateText() function. This value is passed through the setInterval() function in the previous exercise.5. Delete the following lines of ActionScript:
my_txt._alpha = 20;
my_txt._y = (Stage.height-my_txt._height)/2;
my_txt.autoSize = true;
my_txt.embedFonts = true;
my_txt.text = my_str;
Now that you have created alternative text fields, you no longer need this testing code.6. Preview the code in your default web browser by pressing F12, as seen in the following figure.
this.createTextField("my_txt",
this.getNextHighestDepth(), 0, 0, 100, 20);
my_txt.setNewTextFormat(txt_fmt);
my_txt._alpha = 20;
my_txt.autoSize = true;
my_txt.border = true;
my_txt.embedFonts = true;
my_txt.text = "lorum ipsum";
Figure 7.11. Press F12 to review your hard work in a browser window. The text strings at the left side of the Stage are expected at this point.

Exercise 6: Animating dynamic text fields
Now that your document adds three dynamic text fields, it is time to add some tweening and animation so they easily glide across the Stage. Using the Tween class lets you not only animate instances with a single line of code, it also lets you choose easing methods so the text field will decrease and increase its speed as it moves across the Stage.
1. Add the following lines of boldface code, which are being added to the bottom of the animateText() function:
This block of code animates the my_txt text field and changes the _x property to slide the text field from left to right over 10 frames. The initial value for the _x property will be set to my_txt._width which causes the text field to appear just off the left side of the Stage, so it slides in from off the screen. Similar to the code that centered the text field vertically in the previous exercise, the text field stops moving just off-center of the horizontal center of the Stage.2. If you test the document right now, you'll notice that each text field animates from left to right and stops around the middle of the Stage (Figure 7.12). You'll add a couple more tweening effects, which will cause the final animation to tween quickly to the middle of the Stage, slowly move 20 pixels from left to right, and then tween off the right edge of the Stage.
function animateText(my_str:String,
interval_index:Number):Void {
clearInterval(interval_array[interval_index]);
var instance_str:String =
"string"+interval_index+"_txt";
root_mc.createTextField(instance_str,
root_mc.getNextHighestDepth(), 0, 0, 100, 20);
var my_txt:TextField = root_mc[instance_str];
my_txt.setNewTextFormat(txt_fmt);
my_txt._alpha = 20;
my_txt._y = (Stage.height-my_txt._height)/2;
my_txt.autoSize = true;
my_txt.embedFonts = true;
my_txt.text = my_str;
var first_tween:Object = new
mx.transitions.Tween(my_txt, "_x", mx.transitions.easing.Regular.easeIn, -my_txt._width,
((Stage.width-my_txt._width)/2)-10, 10, false);
}
Figure 7.12. Text stops around the middle of the Stage.

This code creates the second tween for each of the three text fields. Again the _x property of the my_txt text field is modified. This time, the text field moves only two pixels from its current position and takes 24 frames, so the animation is much slower. Test the document again in an external browser to see the second animation.4. Return to Flash and increase the frame rate from the default frame rate of 12 fps to 24 fps. This causes the animation to be a bit smoother and also tween much quicker because doubling the frame rate causes the animations to take half as much time to tween. At 24 fps, each animation should be finished tweening before the next text field appears on the Stage.5. Add the following boldface code within the first_tween.onMotionFinished event handler function you added in step 3:
function animateText(my_str:String,
interval_index:Number):Void {
clearInterval(interval_array[interval_index]);
var instance_str:String =
"string"+interval_index+"_txt";
root_mc.createTextField(instance_str,
root_mc.getNextHighestDepth(), 0, 0, 100, 20);
var my_txt:TextField = root_mc[instance_str];
my_txt.setNewTextFormat(txt_fmt);
my_txt._alpha = 20;
my_txt._y = (Stage.height-my_txt._height)/2;
my_txt.autoSize = true;
my_txt.embedFonts = true;
my_txt.text = my_str;
var first_tween:Object = new
mx.transitions.Tween(my_txt, "_x", mx.transitions.easing.Regular.easeIn, -my_txt._width,
((Stage.width-my_txt._width)/2)-10, 10, false);
first_tween.onMotionFinished = function() {
var second_tween:Object = new
mx.transitions.Tween(my_txt, "_x", mx.transitions.easing.None.easeInOut, my_txt._x,
my_txt._x+20, 24, false);
};
}
This code waits for the second motion tween to finish and then uses the continueTo() method to tween each text field off the Stage by moving to the Stage width. Because the registration point for each text field is located in the upper-left corner, setting the _x coordinate to the width of the Stage causes the instance to sit just off the right of the Stage so it's no longer displayed. The last couple lines of code within the event handler delete the onMotionFinished event handlers for both the first_tween and second_tween objects. The text fields are off of the Stage and no longer visible, so you don't need the event handlers now.6. Test the final animation in your default web browser. If you find the animations move too quickly or too slowly, you can either modify the frame rate or increase the number of frames that the tweens take. If you find that some text fields are long and overlap while tweening, you can increase the intervals in the setInterval() function and give them an extra few hundred milliseconds.
first_tween.onMotionFinished = function() {
var second_tween:Object = new
mx.transitions.Tween(my_txt, "_x", mx.transitions.easing.None.easeInOut, my_txt._x,
my_txt._x+20, 24, false);
second_tween.onMotionFinished = function() {
second_tween.continueTo(Stage.width, 10);
delete first_tween.onMotionFinished;
delete second_tween.onMotionFinished;
};
};
Make sure that you save the changes you made to the file.