如何在方法中使用递归setTimeout

时间:2015-01-05 05:44:01

标签: javascript prototype settimeout

我试图在方法内使用setTimeout()作为递归函数。我假设我正在使用'这个'范围错误但是。这是一个例子。

(function(scope){
    function gamePlay(){
       // this.initialize();
    }

    gamePlay.prototype.droidMovement = function(){
        console.log('droid is moving');
        this.droidShoot();
    }    

    gamePlay.prototype.droidShoot = function(){
        console.log('droidShoot() has been fired');
        setTimeout(this.droidShoot,1000);
    }   

scope.gamePlay = gamePlay;    
})(window);

var game = new gamePlay();
game.droidMovement();

我尝试过setTimeout 3种方法。

//this way repeats the function 2 times then stops
setTimeout(this.droidShoot,1000);

//this gives me an error
setTimeout(function(){this.droidShoot()},1000);

//this fires the function in a loop but doesnt wait the second
setTimeout(this.droidShoot(),1000);

任何人都可以解释一下我做错了什么吗?非常感谢提前。

1 个答案:

答案 0 :(得分:-1)

您可能希望从setTimeout的定义中删除droidShoot,并将setTimeout(this.droidShoot, 1000)替换为setInterval(this.droidShoot, 1000

setInterval将以1s间隔重复自动调用this.droidShoot