Repeating an action

ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the while, do..while, for, and for..in actions to create loops.

To repeat an action while a condition exists:

A while loop evaluates an expression and executes the code in the body of the loop if the expression is true. After each statement in the body is executed, the expression is evaluated again. In the following example, the loop executes four times:

i = 4;
while (var i > 0) {
  my_mc.duplicateMovieClip("newMC" + i, i );
  i--;
}

You can use the do..while statement to create the same kind of loop as a while loop. In a do..while loop, the expression is evaluated at the bottom of the code block so the loop always runs at least once, as shown in the following example:

i = 4;
do {
  my_mc.duplicateMovieClip("newMC" +i, i );
  i--;
} while (var i > 0);

To repeat an action using a built-in counter:

Most loops use a counter of some kind to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. In the for action, the counter and the statement that increments the counter are part of the action. In the following example, the first expression (var i = 4) is the initial expression that is evaluated before the first iteration. The second expression (i > 0) is the condition that is checked each time before the loop runs. The third expression (i--) is called the post expression and is evaluated each time after the loop runs.

for (var i = 4; i > 0; i--){
  myMC.duplicateMovieClip("newMC" + i, i + 10);
}

To loop through the children of a movie clip or object:

Children include other movie clips, functions, objects, and variables. The following example uses the trace statement to print its results in the Output panel:

myObject = { name:'Joe', age:25, city:'San Francisco' };
for (propertyName in myObject) {
  trace("myObject has the property: " + propertyName + ", with the value: " + myObject[propertyName]);
}

This example produces the following results in the Output panel:

myObject has the property: name, with the value: Joe
myObject has the property: age, with the value: 25
myObject has the property: city, with the value: San Francisco

You may want your script to iterate over a particular type of child—for example, over only movie clip children. You can do this with for..in in conjunction with the typeof operator.

for (name in myMovieClip) {
  if (typeof (myMovieClip[name]) == "movieclip") {
    trace("I have a movie clip child named " + name);
  }
}

For more information on each action, see individual entries in ActionScript Dictionary Overview.