1.7. Repeating a Task at Timed Intervals
Problem
You want to perform an action or actions at a specific timed interval.
Solution
Use the setInterval( )
function.
Discussion
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 thatsomeFunction( )is called approximately once per second. // AssignsetInterval( )'s return value to the variablemyIntervalID
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access