Working with setInterval in classes


As you know flash doesn’t have threads. So if you want to have some commands that execute in time intervals you must use set Interval. But there is a problem. SetInterval a acts independently. It means it doesn’t see it’s global variables. Lets try:

Make a new action script file (File -> New -> Action Script File) copy and paste the following into it:

class Test {
var t1 = 10;
var interval;
function Test() {
trace(t1);
interval = setInterval(increase, 10);
}
function increase() {
t1++;
_root.t1 = t1;
if (t1 == 100) {
clearInterval(interval);
}
}
}


Analyze:

The class has two properties. T1 that we assign it to 3 and interval. The class constructor trace(t1) then call incease function in 10ms intervals and assign the setInterval id to interval property.
The increase function add t1 by 1 and set the t1 variable of root to it.Also it checks if t1 is equal to 100 then clearInterval.For testing our script we must make a new fla file and create a dynamic text field with variable t1.Also copy this in the action of 1st frame:
var t:Test=new Test()
Now publish it.You can only see the t1=undefined


So what did happen???
Setinterval can’t see the property of its class. What to do? There are several solutions for it. For example you can send the t to increase. But what if you add other properties to your class then you must add them to setInterval params section.

The Solution
For this purpose I suggest to send you object to the function then set this variable of function. That’s it. Then if you want to add 100 other properties there is no need to change the function prototype

Change the code as this:

class Test {
var t1 = 10;
var interval;
function Test() {
trace(t1);
interval = setInterval(increase, 10,this);
}
function increase(_this) {
this=_this
t1++;
_root.t1 = t1;
if (t1 == 100) {
clearInterval(interval);
}
}
}


As you see everything works fine. The function increase the t starting 10 and clearInterval on t=100.Hope it would be useful.