React with setTimeout

React with setTimeout
0

#1

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?


#2

You’re calling resetCards directly. Try this:

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

#3

Yep, that did it!

Thanks so much!