Ryan
Ryan

Reputation: 10049

Javascript: settimeout problem

When I start my script I have this:

var my_great_masterpiece = new function ()
{
        var self = this;

Then later in my script I have this:

        response_xml: function ()
        {
            if (self.http_request.readyState == 4)
            {
                if (self.http_request.status == 404 && countXmlUrl <= 3)
                {
                    countXmlUrl++;
                    self.realXmlUrl = xmlUrl[countXmlUrl];
                    self.request_xml();
                }
                if (self.http_request.status == 200)
                {
                    self.xmlDoc = self.http_request.responseXML;
                    self.storage.setItem('domains_raw_xml', self.http_request.responseText);
                    self.main.peter_save_data();
                    self.timervar = setTimeout(function ()
                    {
// ########### Below line gives the error #############################
                        self.new_version_show_window();
                    }, 2000);
                }
            }
        },
        new_version_show_window: function ()
        {
...
}

the error that I am getting is:

Error: self.new_version_show_window is not a function

What am I doing wrong?

Thanks!

Upvotes: 0

Views: 733

Answers (3)

Magnar
Magnar

Reputation: 28810

It is unclear from your code where new_version_show_window is defined. Maybe you could explicitly define it on self:

self.new_version_show_window = function () {
    /* ... */
}

instead. Or you could define it in the local namespace and use it directly in the setTimeout call:

self.timervar = setTimeout(function () {
    new_version_show_window();
 }, 2000);

or simply:

self.timervar = setTimeout(new_version_show_window, 2000);

Because of closure, the variables declared in the outer function is also available in the inner function.

Edit

Thanks for posting the entire code. new_version_show_window is defined on this.main, so you must access it thusly:

self.timervar = setTimeout(function () {
    self.main.new_version_show_window();
 }, 2000);

Upvotes: 5

George Cummins
George Cummins

Reputation: 28906

This is a problem of scope. new_version_show_window is only in scope in the construct in which is it called ( apparently a jQuery AJAX function of some sort). It will only be available to my_great_masterpiece if you define it outside the limited scope in which it now exists.

Upvotes: 0

Jivings
Jivings

Reputation: 23250

It could be that self is a reserved word in JavaScript [1]. This could be causing you some problems so try naming the variable something different to start with.

[1] http://www.quackit.com/javascript/javascript_reserved_words.cfm

Upvotes: 0

Related Questions