setInterval( ) Global Function

ActionScript for Flash MX: The Definitive Guide, 2nd Edition
By Colin Moock
Chapter 18.  ActionScript Language Reference
setInterval( ) Global Function Flash 6

execute a function or method every n milliseconds
setInterval(function, interval, arg1, arg2,...argn) setInterval(object, method, interval, arg1, arg2,...argn)

Arguments

function

A reference to the function to execute.

interval

The amount of time between function or method executions, in milliseconds.

arg1,...argn

A list of optional arguments to pass to function or method.

object

An object whose method will be executed every interval milliseconds.

method

The string name of the method to execute (must be defined on object).

Returns

An interval identifier, used to stop the timed execution of function or method (which is called "clearing the interval").

Description

The setInterval( ) function starts an interval, which executes the specified function or method every interval milliseconds. Here we start a very simple interval that executes the function helloWorld( ) once per second:

function helloWorld () {   trace("Hello world!"); } setInterval(helloWorld, 1000);  // 1000 milliseconds is 1 second

Notice that the function reference, helloWorld, is specified without the function call operator, ( ). The following attempt to set an interval fails because the call operator is included erroneously:

setInterval(helloWorld(), 1000);  // Oops! Use helloWorld, not helloWorld().

We can also pass a function literal to setInterval( ). For example:

setInterval(function () {trace("Hello world!");}, 1000);

Arguments can be provided to the specified function after the interval parameter:

function hello (person) {   trace("Hello, " + person); } setInterval(hello, 1000, "Mr. Thilgen");

However, the arguments provided are evaluated only once, when the interval is initialized. For example, the following code mistakenly attempts to position a movie clip under the mouse pointer by passing the pointer's location to the interval function:

function followMouse (clip, mousex, mousey) {   clip._x = mousex;   clip._y = mousey; } // Won't work because _root._xmouse and _root._ymouse are evaluated only once setInterval(followMouse, 100, trailer_mc, _root._xmouse, _root._ymouse);

In the corrected version, we retrieve data that changes between function invocations inside the function itself:

function followMouse (clip) {   // Check _root._xmouse and _root._ymouse inside function   clip._x = _root._xmouse;   clip._y = _root._ymouse; } setInterval(followMouse, 100, trailer_mc);

The alternative syntax of the setInterval( ) function invokes a method on an object periodically. The following code executes the nextFrame( ) method of the main timeline (_root) every quarter-second, creating a slideshow effect:

setInterval(_root, "nextFrame", 250);

Remember to specify the method name as a string, not as a function reference!

When setInterval( ) is passed a function reference, the value of the this keyword within the function is undefined:

function showThis () {   trace(this); } setInterval(showThis, 100);  // 'this' will be undefined

However, when setInterval( ) is passed an object reference and a method name, the value of the this keyword is the object passed as the first argument:

setInterval(_root, "showThis", 100); // 'this' will be a reference to _root

When an interval is created, it is assigned an ID (interval identifier) that is returned by setInterval( ). This ID should be stored in a variable so that the interval can later be stopped with clearInterval( ), as follows:

// Start the interval var intervalID = setInterval(someFunction, 50); // Stop the interval some time later clearInterval(intervalID);

Often, the interval is cleared inside the function specified in the original setInterval( ) call:

var counter = 1; function countToTen () {   trace(counter);   // If we've made it to ten...   if (counter =  = 10) {     // ...stop the interval     clearInterval(counterInterval);   }   counter++; }     // Start the interval var counterInterval = setInterval(countToTen, 200);

If the interval ID is not stored, the interval can never be stopped. In Flash 6, interval IDs are integer values, but you should not stop intervals by guessing their numeric interval ID. The ID architecture is internal and subject to change in the future. To stop a group of intervals en masse, store their IDs in an array and use clearInterval( ) on each element.

Note that overwriting a variable that contains an interval ID does not clear the interval (which keeps running). Intervals can be cleared only via clearInterval( ). For example, in the following code, the variable intervalID is assigned two interval IDs, but both functionA( ) and functionB( ) continue to run every 100 ms, and intervalID stores the ID of the second interval only:

var intervalID = setInterval(functionA, 100); var intervalID = setInterval(functionB, 100); // The variable intervalID now contains the second interval ID, but // the first interval still runs (and cannot be stopped!)

The setInterval( ) function provides a time-based alternative to the onEnterFrame( ) MovieClip handler, which executes code once for every tick of the frame rate. However, setInterval( ) is still dependent on the frame rate of a movie. An interval can run 10 times per frame at most. So, even in a movie with a frame rate of 1 frame per second, an interval can still run only 10 times per second (every 100 ms) at most, even when a smaller interval value is specified. Theoretically, at 10 frames per second, an interval can run 100 times per second (10 times per frame x 10 frames per second), or every 10 ms. To update the screen within an interval function that runs more often that the frame rate, call updateAfterEvent( ) from within the function or method that the interval executes. For example:

function moveClip (clip) {   // Move the clip   clip._x += 5;   // Update the screen   updateAfterEvent(); }     setInterval(moveClip, 1, ball_mc);

When an interval is set to run less often than the duration of a tick of the frame rate, it will execute on the frame after the interval time has expired. For example, given an interval set to 400 ms and a frame rate of 10 fps (1 frame per 100 ms), Table 18-16 shows the frames on which the interval should execute.

Table 18-16. Interval execution relative to frame display

Frame number

Total time (milliseconds)

Interval executed?

0

0

no

1

100

no

2

200

no

3

300

no

4

400

yes

5

500

no

6

600

no

7

700

no

8

800

yes

9

900

no

10

1000

no

However, whether an interval runs more or less often than the frame rate of a movie, interval times are by no means guaranteed. In an actual test movie, the intervals in Table 18-16 may execute at frames 5 and 9, or even at frames 4 and 9. Code execution, Player rendering, and available system resources can all affect the actual timing of intervals. Where time is an important factor in an application (for example, in a game), functions should be written to account for variance in interval times.

Usage

There is no JavaScript-style setTimeout( ) function in ActionScript. To emulate setTimeout( ), create an interval function that clears itself the first time it runs, as shown in the following Example.

Example

The following code shows a simple timer that executes after 5 seconds and never executes again:

function timesUp () {   trace("Time's up!");   // Stop the timer   clearInterval(timerInterval); } timerInterval = setInterval(timesUp, 5000);

See Also

clearInterval( ), MovieClip.onEnterFrame( )



    ActionScript for Flash MX. The Definitive Guide
    ActionScript for Flash MX: The Definitive Guide, Second Edition
    ISBN: 059600396X
    EAN: 2147483647
    Year: 2002
    Pages: 780
    Authors: Colin Moock

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net