0

Im trying to use setTimeout() for a recursive function, inside a method. I'm assuming I'm getting something with the 'this' scope wrong though. Here's an example.

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

Ive tried the setTimeout 3 ways.

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

Can anyone please explain what I'm doing wrong? thanks so much in advance.

nickg
  • 151
  • 2
  • 11

1 Answers1

-1

You may want to remove the setTimeout from within the definition of droidShoot and replace setTimeout(this.droidShoot, 1000) with setInterval(this.droidShoot, 1000.

setInterval will automatically call this.droidShoot repeatedly at a 1s interval

jtmarmon
  • 5,727
  • 7
  • 28
  • 45
  • thanks Jason. I just found an answer allowing for the use of setTimeout.http://stackoverflow.com/questions/5911211/settimeout-inside-javascript-class-using-this – nickg Jan 05 '15 at 06:00