0

I'm trying to do a recursive loop but I'm facing some issues. I have issues with the 'this'.

I first started without the if statement, I had issues with the recursive call so I binded the this.play then it worked.

But, since I wanted to had a pause I added the if statement and now everything is broken.

I'm open to solutions, thank you :)

class Game {
    constructor() {
        this.turn = 0;
        this.play = this.play.bind(this);
    }

    play(state) {
        if (state) {
            this.turn ++;
            console.log(this.turn);
            setTimeout(this.play, 2000);
        } else {
            console.log(this.turn);
        }
    }
}
M_DWWM
  • 1
  • "*But, since I wanted to had a pause I added the if statement and now everything is broken.*" can you explain what is the expected result and what is currently happening? Any errors? – VLAZ Mar 22 '21 at 14:07
  • 2
    The `state` parameter does not get passed when you use `setTimeout`. [How can I pass a parameter to a setTimeout() callback?](https://stackoverflow.com/a/1190656) – 001 Mar 22 '21 at 14:09
  • @JohnnyMopp Thank you so much ! It works ! For the solution I changed the `setTimeout` to this : `setTimeout(() => this.play(state), 2000);` – M_DWWM Mar 22 '21 at 14:13

0 Answers0