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.

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 ...

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.