views:

307

answers:

1

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?

+3  A: 

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;
    }
}
Gabriel McAdams
Remember to accept this answer if you found it useful.
Gabriel McAdams
When calling the function as set up in your example i was passing in "this" like so testing(this); it was undefined. You did remind me that AS2 has support for eval so i simply changed this["btn"+a] to eval("btn"+a) and it works. so many thanks for the reminder :)
Kohan
I'm glad you found a solution. Please accept this answer if you felt it was helpful.
Gabriel McAdams
If I could just add a suggestion, using Delegate will fix the scoping issue and you won't need to use hacks like eval():myTimer = setInterval(Delegate.create(this, testing), 3000);This will still call testing() when the timer fires, but the scope will be 'this', so Kohan's original function would work.
wmid
Good comment. I will modify my answer with more information.
Gabriel McAdams