start page | rating of books | rating of authors | reviews | copyrights

Book HomeActionScript: The Definitive GuideSearch this book

8.6. Stopping a Loop Prematurely

In a simple loop, the test expression is the sole factor that determines when the loop stops. When the test expression of a simple loop yields false, the loop terminates. However, as loops become more complex, we may need to arbitrarily terminate a running loop regardless of the value of the test expression. To do so, we use the break and continue statements.

8.6.1. The break Statement

The break statement ends execution of the current loop. It has the modest syntax:

break

The only requirement is that break must appear within the body of a loop.

The break statement provides a way to halt a process that is no longer worth completing. For example, we might use a for-in loop to build a form-checking routine that cycles through the input-text variables on a timeline. If a blank input field is found, we alert the user that she hasn't filled in the form properly. We can abort the process by executing a break statement. Example 8-3 shows the code. Note that the example assumes the existence of a movie clip called form that contains a series of declared input variables named input01, input02, and so on.

Example 8-3. A Simple Form-Field Validator

for (var prop in form) {
  // If this property is one of our "input" text fields
  if (prop.indexOf("input") != -1) {
    // If the form entry is blank, abort the operation
    if (form[prop] == "") {
      displayMessage = "Please complete the entire form.";
      break;
    }
    // Any substatements following the break command are not reached
    // when the break is executed
  }
}
// Execution resumes here after the loop terminates whether
// due to the break command or the test condition becoming false

You can use the break statement to interrupt a loop that would otherwise be infinite. This allows you to perform, say, the statements in the first half of the code block without necessarily executing the statements following an if (condition) break ; statement. The generic approach is shown in Example 8-4.

Example 8-4. Breaking out of an Infinite Loop

while (true) {
  // Initial statements go here
  if (condition) break;
  // Subsequent statements go here
}

8.6.2. The continue Statement

The continue statement is similar to the break statement in that it causes the current iteration of a loop to be aborted, but unlike break, it resumes the loop's execution with the next natural cycle. The syntax of the continue statement is simply:

continue

In all types of loops, the continue statement interrupts the current iteration of the loop body, but the resumption of the loop varies slightly depending on the type of loop statement. In a while loop and a do-while loop, the test expression is checked before the loop resumes. But in a for loop, the loop update is performed before the test expression is checked. And in a for-in loop, the next iteration begins with the next property of the object being inspected (if one exists).

Using the continue statement, we can make the execution of the body of a loop optional under specified circumstances. For example, here we move all the movie clip instances that aren't transparent to the left edge of the Stage, and we skip the loop body for transparent instances:

for (var prop in _root) {
  if (typeof _root[prop] == "movieclip") {
    if (_root[prop]._alpha < 100) {
      continue;
    }
    _root[prop]._x = 0;
  }
}

8.6.3. Maximum Number of Iterations

As noted earlier, loops are not allowed to execute forever in ActionScript. In the Flash 5 Player loops are limited to 15 seconds. The number of iterations that can be achieved in that time depends on what's inside the loop and the computer's speed. To be safe, you shouldn't create loops requiring more than even a few seconds to execute (which is eons in processing terms!). Most loops should take only milliseconds to finish. If a loop takes longer to complete (for example, because it's processing hundreds of strings while initializing a word-scramble game), it's worth rewriting the code using a timeline loop, as described in Section 8.7, "Timeline and Clip Event Loops". Timeline loops allow us to update the progress of a script's execution on screen and avoid the potential display of the error message shown in Figure 8-1.

Figure 8-1

Figure 8-1. Bad loop! Down boy!

When a loop has run for more than 15 seconds in the Flash 5 Player, an alert box warns the user that a script in the movie is delaying the movie's playback. The user is offered the choice to either wait for the script to finish or to quit the script.

The Flash 4 player is even stricter -- it allows only 200,000 iterations -- after which all scripts are disabled without any warning.

WARNING

Take special heed: the 15-second warning that users see does not mention that canceling a runaway script will actually cause all scripts in the movie to stop functioning! If a user selects "Yes" to stop a loop from continuing, all scripts in the movie are disabled.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.