View comments | RSS feed

setInterval()

Availability

Flash Player 6.

Usage

setInterval(functionName:Function, interval:Number [, param1:Object, param2, ..., paramN]) : Number

Parameters

functionName A function name or a reference to an anonymous function.

interval The time in milliseconds between calls to the functionName parameter.

param1, param2, ..., paramN Optional parameters passed to the function or methodName parameter.

Returns

An identifying integer that you can pass to clearInterval() to cancel the interval.

Description

Function; calls a function or a method or an object at periodic intervals while a SWF file plays. You can use an interval function to update variables from a database or to update a time display.

If interval is less than the SWF file's frame rate (for example, 10 frames per second [fps] is equal to 100 milliseconds), the interval function is called as close to interval as possible. You must use the updateAfterEvent() function to make sure that the screen refreshes often enough. If interval is greater than the SWF file's frame rate, the interval function is only called each time the playhead enters a frame; this minimizes the impact each time the screen is refreshed.

Example

Usage 1: The following example calls an anonymous function every 1000 milliseconds (1 second).

setInterval( function(){ trace("interval called"); }, 1000 );

Usage 2: The following example defines two event handlers and calls each of them. Both calls to setInterval() send the string "interval called" to the Output panel every 1000 milliseconds.The first call to setInterval() calls the callback1() function, which contains a trace() statement. The second call to setInterval() passes the "interval called" string to the function callback2() as a parameter.

function callback1() {
   trace("interval called"); 
}

function callback2(arg) { 
   trace(arg);
}

setInterval( callback1, 1000 ); 
setInterval( callback2, 1000, "interval called" );

Usage 3: This example uses a method of an object. You must use this syntax when you want to call a method that is defined for an object.

obj = new Object();
obj.interval = function() { 
   trace("interval function called"); 
}

setInterval( obj, "interval", 1000 ); 

obj2 = new Object();
obj2.interval = function(s) { 
   trace(s); 
}
setInterval( obj2, "interval", 1000, "interval function called" ); 

You must use the second form of the setInterval() syntax to call a method of an object, as shown in the following example:

setInterval( obj2, "interval", 1000, "interval function called" ); 

When working with this function, you need to be careful about the memory you use in a SWF file. For example, when you remove a movie clip from the SWF file, it will not remove any setInterval() function running within it. Always remove the setInterval() function by using clearInterval() when you have finished using it, as shown in the following example:

// create an event listener object for our MovieClipLoader instance
var listenerObjectbject = new Object();
listenerObject.onLoadInit = function(target_mc:MovieClip) {
   trace("start interval");
   /* after the target movie clip loaded, create a callback which executes about every 1000 ms (1 second) and calls the intervalFunc function. */
   target_mc.myInterval = setInterval(intervalFunc, 1000, target_mc);
};
function intervalFunc(target_mc) {
   // display a trivial message which displays the instance name and arbitrary text.
   trace(target_mc+" has been loaded for "+getTimer()/1000+" seconds.");
   /* when the target movie clip is clicked (and released) you clear the interval and remove the movie clip. If you don't clear the interval before deleting the movie clip, the function still calls itself every second even though the movie clip instance is no longer present. */
   target_mc.onRelease = function() {
      trace("clear interval");
      // clearInterval(this.myInterval);
      // delete the target movie clip
      removeMovieClip(this);
   };
}
var jpeg_mcl:MovieClipLoader = new MovieClipLoader();
jpeg_mcl.addListener(listenerObject);
jpeg_mcl.loadClip("http://www.macromedia.com/software/central/images/klynch_breezo.jpg", this.createEmptyMovieClip("jpeg_mc", this.getNextHighestDepth()));

If you work with setInterval() within classes, you need to be sure to use the this keyword when you call the function. The setInterval() function does not have access to class members if you do not use the keyword. This is illustrated in the following example. For a FLA file with a button called deleteUser_btn, add the following ActionScript to Frame 1:

var me:User = new User("Gary");
this.deleteUser_btn.onRelease = function() {
   trace("Goodbye, "+me.username);
   delete me;
};

Then create a FLA in the same directory called User.as. Enter the following ActionScript:

class User {
   var intervalID:Number;
   var username:String;
   function User(param_username:String) {
      trace("Welcome, "+param_username);
      this.username = param_username;
      this.intervalID = setInterval(this, "traceUsername", 1000, this.username);
   }
   function traceUsername(str:String) {
      trace(this.username+" is "+getTimer()/1000+" seconds old, happy birthday.");
   }
}

See also

clearInterval(), updateAfterEvent()

Comments


Francis Cheng said on Aug 16, 2004 at 10:06 AM :
In the last two examples in Usage 3 of the Example section, clearInterval() is not properly called. First, in the function IntervalFunc(), the call to clearInterval in the onRelease handler should not be commented out (please remove the pair of slashes):
// clearInterval(this.myInterval);

Second, in the example that creates an instance of the User class, the onRelease handler for the deleteUser_btn should include a call to clearInterval() before the object is deleted:
this.deleteUser_btn.onRelease = function() {
trace("Goodbye, "+me.username);
clearInterval(me.intervalID);
delete me;
};
rowdypig said on Dec 1, 2004 at 11:16 AM :
About 2/3 of the way down the text, as part of the clearInterval example, the following typographical error exists:

var listenerObjectbject = new Object();

it should be:

var listenerObject=newObject();
webweber@bluewin.ch said on Jan 7, 2005 at 5:34 AM :
When calling a class method in an interval from a *timeline*, use this syntax:

intID = setInterval(myClassInstance, 'someMethod', 100);

There are other ways to call the method, but this seems to be the only syntax to successfully listen for an event the class might dispatch.

(PS: "Then create a FLA in the same directory called User.as." should be "Then create a .as file")

Andreas Weber
Francis Cheng said on Jan 16, 2005 at 9:17 PM :
Thanks rowdypig and Andreas,
Those mistakes are now fixed in the documentation source files.
jaseinatl@gmail.com said on Jan 22, 2005 at 10:52 PM :
It would really be helpful if you picked a naming convention (and stuck with it) when documenting examples.

Provided Example 2, Usage 3:
---------------------------------------------------------------------------------
obj.interval = function() {
trace("interval function called");
}
setInterval( obj, "interval", 1000 );
obj2 = new Object();
obj2.interval = function(s) {
trace(s);
}
setInterval( obj2, "interval", 1000, "interval function called" );
-----------------------------------------------------------------------------------------
Although "obj" is not a reserved word, it is difficult to distinguish it as an instance-creating Object because of the non-specific field name. By using 'someObject' (or even 'someObj'), the reader understands that this is an arbitrary label rather than a built-in method/function.

The same is true with "interval" which is syntactically legal to use it in the above example to define a function. The problem, however, is that it is unclear whether the author intended to use "interval" as some arbitrary label for a function or whether "interval" is an as-of-yet undocumented method of the Object class that is being hijacked for the example. In other words, upon first reading this help file, it may appear that the "interval" function decalration in Example 2, Usage 3 is being used to show how to reroute an intrinsic function "interval".

It would be more approriate, for example to use the following conventions:

========================================================
someObj = new Object();
someObj.someLabel = "User Object 1 (someObj)";
someObj.someIntervalFunct = function() {
trace ("");
trace("The user-defined function 'someIntervalFunct'");
trace ("was called by "+someObj.someLabel);
};
setInterval(someObj, "someIntervalFunct", 1000);
anotherObj = new Object();
anotherObj.someLabel = "User Object 2 (anotherObj)";
anotherObj.someIntervalFunct = function(someString:String) {
trace ("");
trace("--------------------------------------------------------------");
trace("The user-defined function 'someIntervalFunct' ");
trace ("was called by "+anotherObj.someLabel);
trace("and shows the usage of 'params' in the intrinsic function ");
trace(" 'setInterval(obj, function, params)' ");
trace("The 'params' passed in this instance were: '"+someString+"'.");
trace("--------------------------------------------------------------");
};
setInterval(anotherObj, "someIntervalFunct", 3000, "Example Params");
========================================================

The OUTPUT window should display :

The user-defined function 'someIntervalFunct'
was called by User Object 1 (someObj)

The user-defined function 'someIntervalFunct'
was called by User Object 1 (someObj)

--------------------------------------------------------------
The user-defined function 'someIntervalFunct'
was called by User Object 2 (anotherObj)
and shows the usage of 'params' in the intrinsic function
'setInterval(obj, function, params)'
The 'params' passed in this instance were: 'Example Params'.
--------------------------------------------------------------
*****************************************************************************

By adding the someObject.someLabel properties, it allowed us to tell which function was doing what when executed.

By varying the interval length from 1000, to 2000 we are able to verify that the interval length parameter was passed correctly.

By changing all of the labels to a convention which indicates the scope of the object being labeled, it is a lot easier to trace.

By including the resultant output in the example text, we can verify that our presumptions are correct...(this also guarantees that there can be NO typos as the output wouldn't have been generated correctly if the original text were copied and pasted because of the typos indicated in LiveDocs)

and Finally, notice that the example output clearly identifies what is going on and who is doing what. That would really help me out a lot.

ONE LAST THING:
I can't stress enough how important it is that the next help files use Syntax Coloring (and ideally would lookup the user's settings and use the custom Syntax Coloring model they defined in Preferences). I mean, Syntax Coloring is designed to help make your code eaiser to debug, shouldn't it be used in the examples for reference?

Thanks for giving us the opportunity to contribute our 2 cents worth by hosting this forum. Best wishes,

Jase
jaseinatl@gmail.com said on Jan 22, 2005 at 11:46 PM :
As If I didn't have enough to say in the last post, here is something else:

I have been having a terrible time getting the setInterval function to work the way I want it to and I can't help but feel that my problems are coming from the files I am using as reference.

I am trying to code using the conventions outlined in AS2.0 and find the majority of your code is AS1.0 focused. In this section, you have included the AS2.0 Class example and I really appreciate it. Unfortunately, the example suffers from the same lack of descriptive labeling that I mentioned earlier and in this explicit example, there the interval function requires a "str" parameter, but the function never uses it.

ORIGINAL with comments:
class User {
// the variable declarations below need the "public" or "private"
// prefix to be in accordance with AS2.0 conventions
var intervalID:Number;
// this name confusing (see previous post)
var username:String;
//name not in sync with AS2.0 naming conventions.
function User(param_username:String) {
//if not required, it is still good form to declare a return type of Void
//it is not good form to use the passed parameter value
//explicitly when it is assigned to a class property
//on the next line.
trace("Welcome, "+param_username);
this.username = param_username;
// use of the keyword "this" is extraneous in the constructor.
this.intervalID = setInterval(this, "traceUsername", 1000, this.username);
}
function traceUsername(str:String) {
//why does this method require that a string is passed?
trace(this.username+" is "+getTimer()/1000+" seconds old, happy birthday.");
// when it isn't even used by the method.
}
}
=======================================================
I think it should've been something like:

class customUser {
private var myIntervalID:Number;
public var userName:String;
function customUser(userName_p:String) {
userName = (userName_p == undefined ? "Invisible Man" : userName_p);
trace("Welcome, "+userName);
var someComment:String = "you have been waiting ";
myIntervalID = setInterval(this, "sendComment", 1000, someComment);
}
function sendComment(comment_p:String):Void {
var fullComment:String = (comment_p == undefined ? "Waiting for " : comment_p);
fullComment +=int(getTimer()/1000)+ " seconds.";
trace(userName+", "+fullComment);
}
function deleteMe():Void {
clearInterval(myIntervalID);
trace (userName+" signing out");
delete this;
}
}

This example demonstrates the way in which a user-defined method of a user class can be accessed by the setInterval function.

Again, SYNTAX COLORING PLEASE!

And thanks for hosting this forum.

Jase
No screen name said on Feb 9, 2005 at 5:19 PM :
Worth to mention that it is always a good practise to clear Interval ID whenever you want to re-use the same interval ID, as using clearInterval(IntervalID) will clear ONLY the last interval created with teh ID, not able to clear duplicated interval created with the same intervalID.

clearInterval(intervalID);
intervalID=setInterval(xxx,xxx,xxx);

Hereunder is an example to show the difference if you have cleared intervalID before re-using it:

// create initial interval during start
var intA:Number = setInterval(addUp,1000);
this.createTextField("txt1",1,110,10,100,25);
this.createEmptyMovieClip("btnStart",10);
this.createEmptyMovieClip("btnStop",20);
txt1.text=0;

btnStart.onRelease=function(){
// clear interval ID with the same variable name is always a good practise
// ***************************************************************
// Enable and disbale the following line to see the difference
// ***************************************************************
//clearInterval(intA);
intA = setInterval(addUp,1000);
trace("IntervalID createded: " + intA);
}

btnStop.onRelease=function(){
trace("IntervalID cleared: " + intA);
clearInterval(intA);
}


/*
============================================
Don't worry about the following code as they are not
the topic we discuss here
============================================
*/

with (this.btnStart){
beginFill(0xff9900,100);
moveTo(20,50);
lineStyle(1,0x0000);
lineTo(100,50);
lineTo(100,80);
lineTo(20,80);
lineTo(20,50);
endFill();
createTextField("txta",11,50,55,60,20);
txta.selectable=0;
txta.text = "Start";
}

with (this.btnStop){
beginFill(0x00ff00,100);
moveTo(120,50);
lineStyle(1,0x0000);
lineTo(200,50);
lineTo(200,80);
lineTo(120,80);
lineTo(120,50);
endFill();
createTextField("txtb",21,150,55,60,20);
txtb.selectable=0;
txtb.text = "Stop";
}

function addUp(){
txt1.text = Number(txt1.text)+ 1;
}
Francis Cheng said on Feb 10, 2005 at 8:29 AM :
Hi,

Thanks for taking the time to post. It sounds like you are clearly frustrated with our documentation, and I'm sorry to hear that. We've been working hard to improve it, and if you have specific ideas on areas where we've dropped the ball, we would definitely appreciate the feedback. For example, jaseinatl@gmail.com made some good points about variable naming and had other specific criticisms that will help us improve the documentation.
UCF NewMedia said on Feb 14, 2005 at 7:11 AM :
The alternative syntax for calling setInterval within classes needs to be added to the usage area of the help, half way down the documentation you find theres another way to call setInterval. something like:

Usage

setInterval(functionName:Function, interval:Number [, param1:Object, param2, ..., paramN]) : Number

setInterval(objectName:Object, "methodName:String", interval:Number [, param1:Object, param2, ..., paramN]) : Number
VIZID said on Mar 7, 2005 at 11:34 AM :
Is there a time limit on setInterval within classes? I've tested the same code within a class as well as a standalone function. Within the class, the interval times out within 60 seconds and then aborts and causes a looping error. Outside of the class, with slightly modified code, the interval runs indefinitely. Why is this happening?
webb_dev said on Jul 20, 2005 at 2:12 PM :
The setInterval function seems to fire its indicated function immediately when called, rather than waiting for the specified delay. My imagination, or operator error?
always_wondering said on Aug 1, 2005 at 12:53 AM :
Yes i am also noticing that the function is processed straight away.

Would like the function to be called only after the indicated time.

I'm looking for a delay function. So i can call different functions with a time delay. These can be called simutaniously. So the usual obj= setInterval(xx,xx,xx); wouldn't really work. As my scripts all would have to keep track of the obj to be able to kill it later...

Thanks for any help
always_wondering said on Aug 1, 2005 at 1:21 AM :
After trying much more, i managed to get the function to call only after the time specified. Realised its some mistake in my scripts that cause it to be called prematurely.

This is what i've got now, but it does seem to be able to clear the Interval.

//Frame one script
function delay(getFunction, intervalName, time) {
time= time*1000;
trace(intervalName);
intervalName = setInterval(_root[getFunction], time, intervalName);
trace(intervalName);
}
function test(intervalName) {
trace("delay ok");
clearInterval(intervalName);
}

//Script on button.
on (press) {
delay("test","abc",2);
}

Also if anyone like to help with the AS2.0 Class descriptive labeling would really appreciate it. Am still new to AS2.0...
Thanks
iiley said on Aug 24, 2005 at 7:53 PM :
Hi, i am wondering the returned ID of setInterval(). Does it will reuse the id which had cleared. If it do not, after i called setInterval Number.MAX_VALUE times, what id will be returned? will it work well that time?

I did a test like this:

//-------------------------------------------------------------------------------------------
function calllBack(){}
for(var i:Number = 0; i<1000; i++){
var id:Number = setInterval(_root, "calllBack", 1000000);
TRACE("ID = " + id);
}
for(var i:Number = 0; i<500; i++){
clearInterval(i+1);
TRACE("clear id = " + (i+1));
}
TRACE("-----------------------------------");
for(var i:Number = 0; i<1000; i++){
var id:Number = setInterval(_root, "calllBack", 1000000);
TRACE("ID = " + id);
}
//----------------------------------------------------------------------------------------

The output is:

ID = 1
ID = 2
......
ID = 1000
-----------------------------------
clear id = 1
clear id = 2
......
clear id = 1000
-----------------------------------
ID = 1001
ID = 1002
......
ID = 2000
-----------------------------------

the id from 1 to 1000 are cleared, but when i setInterval after that, i can't see they are reused, so ... if the ids can't be reused, when i made more than max number of a Number times, what will happen?

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flash/mx2004/main_7_2/00001662.html