Why won't this Javascript method keep calling itself?

前端 未结 4 1994
無奈伤痛
無奈伤痛 2021-01-18 14:12

I have a JavaScript object with a privileged method. When this method has completed, I would like it to call itself (after a small timeout) and continue running indefinitely

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 15:11

    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);
        };
    }
    

    or use setInterval.

提交回复
热议问题