10.8. Creating Timers and Clocks

Problem

You want to create a timer or perform actions at set intervals.

Solution

Use the setInterval( ) function.

Discussion

This recipe explains how to perform actions at set intervals and create a clock showing the absolute time. Refer to Recipe 10.6 for details on creating timers that show the elapsed time.

The setInterval( ) function, added in Flash MX, lets you set up a timer that calls a function or a method at a specific time interval. The function returns a reference to the interval so that you can abort the action in the future. You can choose from several variations depending on how you want to use setInterval( ). If you want to call a function at a specific interval without passing it any parameters, you can call setInterval( ) with a reference to the function and the number of milliseconds between function invocations.

// This example uses the custom format(  ) method, so it requires the Date.as file.
#include "Date.as"

// This function is called by setInterval(  ), and it displays the current time.
function displayTime(  ) {
  var d = new Date(  );
  trace(d.format("hh:mm a"));
}

// This example invokes displayTime every 60,000 milliseconds (once per minute).
dtInterval = setInterval(displayTime, 60000);

Tip

The setInterval( ) function invokes the function or method at approximately the specified interval. The interval between calls is dependent on the processor of the client computer and is not exact or consistent.

You can also use setInterval( )

Get Actionscript Cookbook 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.