Why won't this Javascript method call itself?

I have a JavaScript object with a privileged method. When this method is completed, I would like it to call itself (after a short timeout) and continue to work indefinitely. Unfortunately, this method only works twice, then it stops without any error (tested in Chrome and IE with the same results).

The code is as follows:

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout(this.testMethod, 2000);
    };
}

var myTest = new Test();
myTest.testMethod();

I would expect to receive an alert every two seconds, but instead, it displays a warning twice and then stops. Here you can see a live example here . Any idea why this is happening?

+5
source share
4

"myTest.testMethod();" "this" "myTest", - , "window" "this", "this.testMethod" "window.testMethod". :

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout((function(self){
            return function(){self.testMethod();};
        })(this), 2000);
    };
}

var myTest = new Test();
myTest.testMethod();

:

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        var self = this;
        setTimeout(function(){self.testMethod();}, 2000);
    };
}

var myTest = new Test();
myTest.testMethod();
+6

this this . :

function Test() {
    // ... private variables that testMethod needs to access ...
    var me = this;
    this.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout(me.testMethod, 2000);
    };
}
+10

Try

function Test() {
    // ... private variables that testMethod needs to access ...
    this.testMethod = function() {
        alert("Hello, from the method.");
        var self = this;
        setTimeout(function() { self.testMethod(); }, 2000);
    };
}

setInterval.

+4

this setTimeout testMethod not Test - , setTimeout( testMethod.testMethod, 2000 )

function Test() {
    // ... private variables that testMethod needs to access ...
    var self = this;
    self.testMethod = function() {
        alert("Hello, from the method.");
        setTimeout(self.testMethod, 2000);
    };
}

var myTest = new Test();
myTest.testMethod();
+3

All Articles