I was born in 1978
I live in Yerevan
I do flash designing/programming for three years
I am studing at American University of Yerevan for my master degree.
By zareh boghozian
Published on April 22, 2007
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...
Working with setInterval in classes
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:
[as]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); } } }[/as]
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:
[as]var t:Test=new Test()[/as]
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:
[as]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]
As you see everything works fine. The function increase the t starting 10 and clearInterval on t=100.Hope it would be useful.