React with setTimeout

Trying to make a portfolio project memory game in react. I’m trying to create a delay after two cards are clicked before they flip back over (if not a match).

I’m using this:

this.timer = setTimeout(this.resetCards(currentTiles, currentScore), 3000);

inside a function, and the resetCards function just resets state and timer:

  resetCards(currentTiles, currentScore) {
    this.setState({
      tiles: currentTiles,
      marked: false,
      firstCard: "",
      firstCardIndex: -1,
      score: currentScore
    });
    clearInterval(this.timer);
  }

In my constructor I also have this bound to both and timer set to null:

this.handleClick = this.handleClick.bind(this);
this.resetCards = this.resetCards.bind(this);
this.timer = null;

But, despite this, the reset function seems to trigger immediately no matter what I do. Ideas?

You’re calling resetCards directly. Try this:

this.timer = setTimeout(() => this.resetCards(currentTiles, currentScore), 3000);
2 Likes

Yep, that did it!

Thanks so much!