Flash - Using SetInterval from a class

Open up your actionscript documentation and find the entry for setInterval…

Scroll right to the bottom, where you get the example

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 follows:
setInterval( obj2, "interval", 1000, "interval function called" );

Ok?

Yeah right...I missed it completely the first time round – In fact what I’ve been doing when using setInterval has been to use something like


_global.myObject = this;
setInterval( function () {_global.myObject.myFunction(), 1000 );

So in effect copying my class into _global and then calling a method from in in-line function. Why? Because ‘this’ when used in the two parameter version of setInterval is undefined.

Obviously it’s a messy way to do things, as you have to realy on the _global variable not being overwritten. However, the third version of setInterval allows you to do something such as

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

from within your class… now setInterval will call your ‘interval’ method of your class, and this will be correctly scoped to the instance…

Post new comment

Please solve the math problem above and type in the result. e.g. for 1+1, type 2
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
More information about formatting options