views:

549

answers:

3

I have a method that uses setTimeOut property and makes a call to another method. On initial load method 2 works fine. However, after timeout, I get an error that says method2 is undefined. What am I doing wrong here?

ex:

test.prototype.method = function()
{
    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);
};

test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }
};
+1  A: 

the "this" you used in setTimeOut is scoping via itself. Create a var "foo = this;" inside your test.prototype.method function and use foo instead.

jason
+7  A: 

The issue is that setTimeout() causes javascript to use the global scope. Essentially, you're calling the method() class, but not from "this". Instead you're just telling setTimeout to use the function "method", with no particular scope.

To fix this you can wrap the function call in another function call that references the correct variables. It will look something like this:

test.protoype.method = function()
{
    var that = this;

    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";

    var callMethod = function()
    {
        that.method();
    }

    timeDelay = window.setTimeout(callMethod, 5000);
};

"that" can be "this" because callMethod() is within method's scope.

This problem becomes more complex when you need to pass parameters to the setTimeout method, as IE doesn't support more than two parameters to setTimeout. In that case you'll need to read up on closures.

Also, as a sidenote, you're setting yourself up for an infinite loop, since method() always calls method().

Daniel Lew
This looks promosing. I will try it out and let you know
DK
Hey, This works in mozilla bu not in ie! any clue? also images do not loop, stops once it reaches the last image
DK
A: 

I get an error that says method2 is undefined

Yes, when you slice off ‘this.method’ from its owner and pass the function alone to setTimeout, you lose the association that sets ‘this’, so ‘this’ in method() is equal to the global object ‘window’.

See this answer for an explanation of the surprising way ‘this’ actually works in JavaScript.

bobince