AS Reference  :  Notes Index  :  Resources  :  About/Contact  :  Downloads

Timers, Intervals & Delays in Flash


An important aspect of any Flash movie is getting the timing of things on stage right. Sometimes this can be done by putting graphics into keyframes on the movie's main timeline, adding tweens where necessary, and dragging the keyframes around to achieve the right visual impact or to make the visuals match music that has been set to Stream in a layer of the movie. In other situations, methods are needed to programmatically control the timing of various events in the movie. Mechanisms which Flash provides to control timing through actionscript include: the onEnterFrame event property of a movieclip, the setInterval function, the getTimer function, and the Tween class. There are also various built-in event properties and listeners which can be used to control the timing of server-related activities (loading text, loading external pictures and videos, etc), which we'll look at in the next section on Dynamic Content.

onEnterFrame

On previous pages, we looked at how to define a function and assign it to the onEnterFrame property of a movieclip (to make bubbles float across the stage in the Dart Shooter game or controls respond smoothly to mouseovers, as in example 5 at the bottom of the Event handlers page and the example at the top of the Group of buttons page). For more examples of onEnterFrame to control movement, see the examples in the Motion section of the Actionscript Reference. Assigning functions to the onEnterFrame event property is a good way to apply the same kind of action to a movieclip (moving it, fading it, or otherwise changing its properties) at the frame rate of the movie.

Tween class

To apply various forms of easing (ease out, bounce, elastic) to a movieclip over some interval, it's easier to use the Tween class and, if necessary, its onMotionFinished method. The Tween class allows you to specify which movieclip you want to affect, which property you want to change over time (eg, _x to move it horizontally, _alpha to fade it, etc), what type of easing you want to apply, what the starting and ending values are for the property to change, and over what amount of time (specified either by number of seconds or number of frames) the change should occur. The Tween class is used to tween the photo slider in the Easing Slider example. An example of assigning a function to its onMotionFinished method (to display a caption when the tweening is complete) is shown in Easing Slider 2.

setInterval function

To change something in a Flash movie at an interval other than the frame rate of the movie (or some multiple of that frame rate), you can use the setInterval function. This function can take one of two forms, one of which (the one most suited to object-oriented programming practices) we'll look at here:

To use setInterval, you first declare a variable of type Number to use as the "handle" for the interval, that is, the thing you'll use to clear it when done. You define the function you want to execute at intervals, or after some delay, and then you use setInterval to call that function after some specified number of milliseconds. The function will be call repeatedly at that same interval until you turn it off with:

To cause an action to be delayed for 5 seconds, eg, use the setInterval and clearInterval together. For example, to check and see whether a person has entered any text into input textfield name_txt within 10 seconds of program startup, and display a message in msg_txt if not:

To do something after a delay

var waitHandle:Number;

function showWarning() {
   if (name_txt.text == "") {
      msg_txt.text = "Please enter your name in the box above";
   }
   clearInterval(waitHandle);
}

waitHandle = setInterval(this, "showWarning", 10000);

An example of using setInterval to call a function repeatedly is shown at the top of the page: to keep track of elapsed time during a movie. Once per second, the number of minutes and seconds that have elapsed since the beginning of the movie are calculated and displayed, using the code below. If you refresh the page, you'll see the count begin again. Check the Math page for more information about Math functions like floor and the Operators page if you don't know what % does.

To do something repeatedly at intervals

var elapsedSeconds:Number;

function showTime() {
   var nMinutes:Number = Math.floor(elapsedSeconds / 60);
   var nSeconds:Number = elapsedSeconds % 60;

   minutes.text = nMinutes;
   seconds.text = nSeconds < 10 ? "0" + nSeconds : nSeconds;
}

function updateTime() {
   elapsedSeconds++;
   showTime();
}

// call showTime to display elapsed time immediately
// then start an interval counter (countInt) to call updateTime once every second
// updateTime will increment the elapsedSeconds counter and re-display the elapsed time
function init() {
   elapsedSeconds = 0;
   showTime();
   countInt = setInterval(this, "updateTime", 1000);
}

init();

getTimer function

getTimer returns the number of milliseconds that have elapsed since the Flash movie began. It's useful for finding the time difference between two events. The following code displays the number of milliseconds between two clicks of button clicker in textfield elapsed_txt. Code like this can be used to detect double-clicks on a button (ie, clicks that happen sequentially between some predetermined amount of time, say within 500 ms of each other), as is done in the next example.

To find the time difference between two events

var clickedOnce:Boolean = false;
var startTime:Number;

function showMsBetweenClicks() {	
   if (!clickedOnce) {
      // first click: save "start time"
      startTime = getTimer();
      elapsed_txt.text = "";
      clickedOnce = true;		
   } else {
      // second click: calculate difference and display
      elapsed_txt.text = getTimer() - startTime;
      clickedOnce = false;
   }
}
	
clicker.onRelease = showMsBetweenClicks;

Double-click detection

Here is an example which combines several of the functions discussed above:

This is the code in frame 1 of that movie:

import mx.transitions.Tween;
import mx.transitions.easing.*;
import mx.utils.Delegate;

var clickedOnce:Boolean = false;
var buttonEnabled:Boolean = true;
var startTime:Number;
var showHandle:Number;
var DOUBLECLICKTIME:Number = 500;   // max time (ms) between clicks for double-click
var TIMETOSHOW:Number = 3;          // number of seconds to display picture
var TIMETOFADE:Number = 2;          // number of seconds to fade picture

// display picture and start timer to call startFade after 3 seconds
function onDoubleClick() {
   // keep user from clicking again til display and fade are done
   buttonEnabled = false;
   pic._alpha = 100;
   showHandle = setInterval(this, "startFade", TIMETOSHOW * 1000);	
}

// uses Tween class to fade picture away over 2 seconds
function startFade() {
   clearInterval(showHandle);
   var tw = new Tween(pic, "_alpha", Strong.easeOut, 100, 0, TIMETOFADE, true);
   tw.onMotionFinished = Delegate.create(this, onFadeFinished);
}

function onFadeFinished() {
   buttonEnabled = true;
   clickedOnce = false;
}

function respondToClick() {	
   if (buttonEnabled) {
      if (!clickedOnce) {
         // first click: save "start time"
         startTime = getTimer();
         clickedOnce = true;		
      } else {
         // second click: calculate difference and display pic if within double-click limits
         if (getTimer() - startTime < DOUBLECLICKTIME) {
            onDoubleClick();
         } 
         clickedOnce = false;
      }
   }
}

function init() {
   pic._alpha = 0;
   showpic.onRelease = respondToClick;
}

init();

The fla is available timers.zip, available as a free download via the link at right. You can vary any of the constants declared at the beginning of the movie to vary the time that defines a double click, the number of seconds the picture stays before fading, and the number of seconds over which the fade occurs.

Intro
Flash: What & How
Example Sites
Create
Draw, Edit Shapes
Gradients
More Drawing Tips
Import
A Sample
Animate
Frames, Keyframes
Motion Tweens
More Motion Tweens
Shape Tweens
Masks
Control
Stop/Replay
Movieclips Intro
Movieclip Reference
Site Structure 1
Slideshow Movieclip
Contact Form
Scroll Resume
Preloader
Site Structure 2
Publish
Display Options
Player Detection
Optimize
AS 2.0 Basics
Intro to Syntax
Playhead Commands
Playhead Cmds 2
Coded Tween
onEnterFrame
Intro to Classes
Declare/Assign
Comments, Trace
Simple Data Types
Arrays & Objects
Code Blocks
Operators
Beyond Buttons
Code Structure
Toggle Controls
Group of Buttons
Drag and Hit
Distort Magnifier
Scroll Text
Bee Game
Dart Shooter
Sound Control
Easing Slider
Easing Slider 2
Components Intro
Timers & Delays
Dynamic Content
Intro
Drawing API
Create Text
Attach Movieclips
Easing Slider 3
Easing Slider 4
Load jpg/swf
Sliding Viewer
Preload swf
XML
Easing Slider 5
Server Comm
LoadVars (w/ PHP)
AS - PHP Lookup
Text File
Database 1:LoadVars
Database 2:Remoting
Read from directory
AS 2.0 Classes
Intro
Math
Key
Date
Color
EventDispatcher
New Samples
Pie Chart
Event-model Emailer
Tween Sequence
Fuse Sequence
SVG in Flash
Bitmap Topo
SWF as Data Holder
Two-level Menu
Yahoo! Flash Maps
Class-based Game
ASTB Samples
Disclaimer
3D Outlines
Bounce Collide
Address Book
Save Drawings
Home  :  Notes Index  :  Resources  :  About/Contact  :  Downloads