ActionScript: Repeating a Task at Timed Intervals

written by: Gabriel Savimbi; article published: year 2007, month 04;



In: Categories » Computers and technology » Flash » ActionScript: Repeating a Task at Timed Intervals

You want to perform an action or actions at a specific timed interval.

Use the setInterval( ) function.

The setInterval( ) function allows you to specify an interval (in milliseconds) at which your Flash movie will invoke a function. Use setInterval( ) to perform a particular action over time but not necessarily at the frequency of the frame rate of the movie.

// Define a function.
   function myIntervalFunction (  ) {
 // Output the difference between the current timer value and its value from the
   // last time the function was called.
   trace(getTimer(  ) - lastTime);
   lastTime = getTimer(  );
   }
// Set up an interval that attempts to invoke myIntervalFunction(  ) once every
   // millisecond.
   setInterval(myIntervalFunction, 1);

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

Don't rely on intervals to be extremely precise.

Don't rely on intervals to be smaller than a few milliseconds.

The setInterval( ) function returns an identifier for the newly created interval. If you want to be able to stop the interval at a later time, you must store the return value, as follows:

// Set an interval such that someFunction(  ) is called approximately once per second.
   // Assign setInterval(  )'s return value to the variable myIntervalID for later use.
   myIntervalID = setInterval(someFunction, 1000);

You can use the clearInterval( ) function to stop an interval if you know the interval's identifier:

clearInterval(myIntervalID);

If you want the interval to invoke the method of an object instead of a standalone function, you can use the variation of the setInterval( ) function in which you pass it three parameters—a reference to the object, the name of the function (as a string), and the interval in milliseconds— instead of just two:

// Create a simple object using the Object constructor.
   obj = new Object(  );
// Assign a method named myMethod to an object, obj.
   obj.myMethod = function (  ) {
   trace("obj.myMethod(  ) has been called");
   };
// Use setInterval(  ) to tell the movie to invoke the myMethod(  ) method of the obj
   // object approximately every six seconds.
   setInterval(obj, "myMethod", 6000);

Whichever variation of the setInterval( ) function you use, any additional parameters that you pass to the setInterval( ) function are passed along to the function or method:

// Define a function that accepts a parameter and displays it in the Output window.
   function displayValue (val) {
   trace(val);
   }
// Use setInterval(  ) to call displayValue(  ) once per minute. The third parameter is 
   // passed to the function when it is called so that each time "Bunny rabbits go 
   // hippity-hop" is displayed in the Output window.
   setInterval(displayValue, 60000, "Bunny rabbits go hippity-hop");

Be aware that any values that you pass to a function or method by way of the setInterval( ) function are evaluated only at the time the interval is initialized. So the same parameter values are always passed to a function or method that is called via setInterval( ):

obj = new Object(  );
obj.traceAnimalName = function (name) {
   trace(name);
   };
myAnimalName = "cub";
setInterval(obj, "traceAnimalName", 30, myAnimalName);
// Even if myAnimalName is assigned a new value, the value "cub" is always passed to
   // traceAnimalName(  ), because myAnimalName was "cub" when setInterval(  ) was first
   // called.
   myAnimalName = "puppy";

One of the neat things you can do with setInterval( ) is create animations that are independent of the movie's frame rate. Remember that the onEnterFrame( ) method executes at the same interval as the frame rate, so using that technique ties you to the movie's properties. But with setInterval( ) you can call a function or method at any interval you want. Here is an example in which two intervals are set—one for a square movie clip (every 50 milliseconds) and one for a circle movie clip (every 100 milliseconds):

// Define the function first. This function takes three parameters: a reference to 
   // the movie clip object, the change in x, and the change in y.
   function moveObj (obj, dx, dy) {
 // Increment the movie clip's x and y coordinates.
   obj._x += dx;
   obj._y += dy;
 // In case the interval is less than the movie's frame rate, you need to use the 
   // built-in updateAfterEvent(  ) method to refresh the Stage.
   updateAfterEvent(  );
   }
// Create two intervals. Each invokes the moveObj(  ) function, but at different 
   // intervals and with different movie clip references as parameters.
   squareInterval = setInterval(moveObj, 50,  square, 1, 1);
   circleInterval = setInterval(moveObj, 100, circle, 1, 1);

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. ActionScript: Filling a Shape with a Gradient
Use the beginGradientFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. In a gradient fill, there is a graded change in colors. Flash supports linear gradients, in which one color fades into the next from left to right. Flash also supports radial gradients, in which the colors radiate out from a center point. You can initiate a gradient-filled shape using beginGradientFill( ) in the same way you initiate a solid-filled shape with beginFill( ). The difference is that the call to beginGradientFill( ) require...

2. Scripting Masks in Flash
Use the Drawing API to create a shape and then use MovicClip.setMask( ) to apply the mask. Masks can be used to create unique shapes or visual effects. For example, you can use masks to create wipes and transitions or interesting animations in which only the masked portion of the artwork is visible at a given time. You can even create masks that change shape over time, and use them to mask bitmapped graphics (in movie clips). You can use any movie clip as a mask of another movie clip using the setMask( ) method. The setMask( ...

3. Drawing a Triangle using ActionScript
Create a custom MovieClip.drawTriangle( ) method using the Drawing API and invoke it on a movie clip. You can determine and plot the vertices of a triangle given the lengths of two sides and the angle between them. This is a better approach than specifying the lengths of the three sides because knowing the lengths of two sides and the angle between them always determines a triangle, whereas three arbitrary sides may not fit together to make a triangle. The custom drawTriangle( ) method accepts six parameters: ab ...

4. ActionScript: Filling a Shape with a Solid or Translucent Color
Use the beginFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. To draw a filled shape, call beginFill( ) prior to any other drawing methods, including the custom methods you have defined such as drawCircle( ) and drawPolygon( ). Invoke endFill( ) after calling other drawing methods to create the shape. You cannot apply a fill to an existing shape drawn at authoring time or runtime. You must invoke beginFill( ) before drawing the shape to be filled. This example creates a solid blue ...

5. Drawing a rectangle using ActionScript
Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter ...

6. How to draw a rectangle with rounded corners
You want to draw a rectangle with rounded corners, an offset, or rotation.Create a custom MovieClip.drawRectangle( ) method using the Drawing API and invoke it on a movie clip. The drawSimpleRectangle( ) method is, as the name suggests, quite simple. Let's create a more complex version that also: Draws a rectangle with a specified angle of rotation Let's you specify the rectangle center's coordinates Can draw a rectangle with rounded corners The drawRectangle( ) method accepts...

7. Reusing and Organizing Code in Flash Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor. Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies: // Adds all the code within MyActionScriptFile.as to your Flash movie. #include "MyActionScriptFile.as" Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file ...

8. Drawing a Circle using ActionScript
Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x =...