Flash AS2 (CS4) - setInterval causing for loop to not work
I have some simple code:
function testing(){
for (a=1; a<=4; a++) {
this["btn"+a].enabled = true;
}
}
If i run this function from anywhere it works fine. If i run this function from myTimer = setInteval(testing, 3000); it will not work. If i add other random code into the function it (the newly added code only) will work. So i have narrowed it down to something about this["btn"+a].enabled = true;
specifically that is causing it to not run.
I really hope this makes sense, appologies, it's 3am :(开发者_如何学编程.
Any ideas?
What you say makes sense. When you call that function normally, "this" is your object. When you run it by using setInterval, you lose the reference to your "this."
- Edited based on comments to help others -
Here are 3 ways to solve this problem:
This way involves passing in "this" to your function:
var that = this;
setInterval(function() {testing(that)}, 1000);
function testing(obj) {
for (a = 1; a <= 4; a++) {
obj["btn" + a].enabled = true;
}
}
This way involves passing in "this" to setInterval:
setInterval(this, "testing", 1000);
function testing() {
for (a = 1; a <= 4; a++) {
this["btn" + a].enabled = true;
}
}
The third way involves the Delagate class:
import mx.utils.Delegate;
setInterval(Delegate.create(this, testing), 1000);
function testing() {
for (a = 1; a <= 4; a++) {
this["btn" + a].enabled = true;
}
}
精彩评论