ActionScript 3.0 Cookbook: Chapter 1: ActionScript Basics
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

In the preceding example, even though the interval is theoretically 500 milliseconds in practice its accuracy and granularity depend on computer playback performance in relation to other tasks demanded of the processor. There are two implications to this:

  • Don't rely on timers to be extremely precise.
  • Don't rely on timer intervals to be smaller than approximately 10 milliseconds.

If you want to emulate the functionality of the setInterval( ) function, set the repeat count to zero. This causes the timer event to fire indefinitely. In this case, the stop( ) method is analogous to the clearInterval( ) function, and stops the timer from firing further events.

Similarly, if you want to duplicate the setTimeout( ) function, set the repeat count to one. The timer waits the specified amount of time, fires one event, and ends.

One of the neat things you can do with the Timer class is create animations that are independent of the movie's frame rate. With a timer you can call a method at any interval you want. Here is an example in which two timers are set--one for a square sprite (every 50 milliseconds)--and one for a circle sprite (every 100 milliseconds):

package {
    import flash.display.Sprite;
    import flash.events.TimerEvent;
    import flash.utils.Timer;
    
    public class ExampleApplication extends Sprite {
        private var _square:Sprite;
        private var _circle:Sprite;
        
        
        public function ExampleApplication( ) {
            // Create the two sprites and draw their shapes
            _square = new Sprite( );
            _square.graphics.beginFill(0xff0000);
            _square.graphics.drawRect(0, 0, 100, 100);
            _square.graphics.endFill( );
            addChild(_square);
            _square.x = 100;
            _square.y = 50;
            
            _circle = new Sprite( );
            _circle.graphics.beginFill(0x0000ff);
            _circle.graphics.drawCircle(50, 50, 50);
            _circle.graphics.endFill( );
            addChild(_circle);
            _circle.x = 100;
            _circle.y = 200;
            
            // Create the two timers and start them
            var squareTimer:Timer = new Timer(50, 0);
            squareTimer.addEventListener(TimerEvent.TIMER, onSquareTimer);
            squareTimer.start( );
            
            var circleTimer:Timer = new Timer(100, 0);
            circleTimer.addEventListener(TimerEvent.TIMER, onCircleTimer);
            circleTimer.start( );
        }
        
        // Define the two handler methods
        private function onSquareTimer(event:TimerEvent):void {
            _square.x++;
        }
        
        private function onCircleTimer(event:TimerEvent):void {
            _circle.x++;
        }
    }
}

It is also possible to use the enterFrame event of a sprite to have some action (or actions) repeat over time. The Timer technique offers some advantages over the enterFrame event method, most notably that it allows you to create intervals that differ from the frame rate of the .swf. With enterFrame, the handling method is called at the frame rate.

With that said, there are still times when using enterFrame is appropriate. For example, you may want something to occur at the frame rate of the .swf. One such scenario is when you want to reverse the playback of the frames in a movie clip.

Section 1.13: Creating Reusable Code

Problem

You want to perform a series of actions at various times without duplicating code unnecessarily throughout your movie.

Solution

Create a method and then call (i.e., invoke) it by name whenever you need to execute those actions. When a function is a member of a class, it is often called a method.

Here is how to create a method of a class:

               accessModifier function functionName ( ):ReturnDataType {
  // Statements go here.
}

To call (i.e., execute) the named method, refer to it by name, such as:

  
               functionName( );

Discussion

Grouping statements into a method allows you to define the method once but execute it as many times as you'd like. This is useful when you need to perform similar actions at various times without duplicating the same code in multiple places. Keeping your code centralized in methods makes it easier to understand (because you can write the method once and then ignore the details when using it) and easier to maintain (because you can make changes in one place rather than in multiple places).


This excerpt is from ActionScript 3.0 Cookbook. Well before Ajax and Windows Presentation Foundation, Macromedia Flash provided the first method for building "rich" web pages. Now, Adobe is making Flash a full-fledged development environment, and learning ActionScript 3.0 is key. That's a challenge for even the most experienced Flash developer. This Cookbook offers more than 300 solutions to solve a wide range of coding dilemmas, so you can learn to work with the new version right away.

buy button

Like class variables, methods can be declared with access modifiers. These determine which other classes are able to call the methods. The available access modifiers are:

private
Can only be accessed from within the class itself.
protected
Can be accessed by the class or any subclass. This is instance-based. In other words, an instance of a class can access its own protected members or those of its superclasses. It cannot access protected members on other instances of the same class.
internal
Can be accessed by the class or any class within the same package.
public
Can be accessed by any class.

The definition of private has changed since ActionScript 2.0, where it allowed access by subclasses. If you do not specify an access modifier explicitly, the method takes on the default internal access.

The following class defines a drawLine method and calls it 10 times, rather than repeating the three lines of drawing code for each line:

package {
    import flash.display.Sprite;

    public class ExampleApplication extends Sprite
    {
        public function ExampleApplication( ) {
            for(var i:int=0;i<10;i++) {
                drawLine( );
            }
        }
    
        private function drawLine( ):void {
            graphics.lineStyle(1, Math.random( ) * 0xffffff, 1);
            graphics.moveTo(Math.random( ) * 400, Math.random( ) * 400);
            graphics.lineTo(Math.random( ) * 400, Math.random( ) * 400);
        }
    }
}

Another important method type is a static method. Static methods aren't available as a member of an instance of that class, but instead are called directly from the class itself. For example, in a class named ExampleApplication, you could define a static method as follows:

public static function showMessage( ):void {
    trace("Hello world");
}

You could then call that method like so:

ExampleApplication.showMessage( );

Some classes contain nothing but static methods. The Math class is an example. Note that you don't have to create a new Math object to use its methods; you simply call the methods as properties of the class itself, such as Math.random( ), Math.round( ), and so on.

Section 1.14: Generalizing a Method to Enhance Reusability

Problem

You want to perform slight variations of an action without having to duplicate multiple lines of code to accommodate minor differences.

Solution

Add parameters to your method to make it flexible enough to perform slightly different actions when invoked rather than performing exactly the same action or producing the same result each time.

Define the parameters that account for the variability in what you want the method to do:

private function average (a:Number, b:Number, c:Number):void {
  trace("The average is " + (c + b + c)/3);
}

If you don't know the exact number of parameters the method will receive, use the built-in arguments array to handle a variable number of parameters.

Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Next Pagearrow