title: setInterval with setState in React
body: <p>I have a timer using <code>setInterval()</code> in a React component and I'm unsure what the best practices are in order to start and stop this interval in respect to using <code>state</code>. I'm running into some asynchronous issues with that.</p>
  
  <p>Let's say I have a set of links in my React component that render and execute the callback fine:</p>
  
  <pre><code>let links = [10, 50, 100, 500, 1000].map((num) =&gt; {
    return(
      &lt;Link key={num} onClick={(e) =&gt; this.switchNums(num)} to={`/somePath/${num}`}&gt;{num}&lt;/Link&gt;
    )
  })
  </code></pre>
  
  <p>Here's the <code>switchNums()</code> function, where i want it to reset an existing timer:</p>
  
  <pre><code>switchNums(num){
    this.stopTimer()
    this.reset(num)
  }
  </code></pre>
  
  <p>Here's <code>startTimer()</code>, <code>stopTimer()</code> and <code>reset()</code>:</p>
  
  <pre><code>startTimer(){
    if(!this.state.timerId){      
      let timerId = setInterval(()=&gt;{
        let timer = this.state.timer + 1
        this.setState({
          timer: timer,
          timerId: timerId
        })
      }, 1000)
    }
  }
  
  stopTimer(){
    clearInterval(this.state.timerId)     
    this.setState({timerId:null})
  }
  
  reset(size){
    this.setState({
      gameOver: false,
      counter: 0,
      correct: 0,
      numbers: this.getRandomNumbers(size),
      timer: 0
    }, this.startTimer())
  }
  </code></pre>
  
  <p>One of the bugs is clicking on the links rapidly will cause multiple intervals to fire despite the <code>if</code> condition in <code>startTimer()</code>. I'm guessing this has to do with the asynchronous nature of <code>setState()</code>. Another bug (and I think related) is that when i click slowly, it only starts the interval every other time. </p>
  
  <p>Can anyone shed some light on this? Or what they've done to circumvent asynchronous issues with <code>setState</code> being used in conjunction with <code>setInterval</code>(any way set state can return a promise?), Or which lifecycle methods would be best for this type of situation?</p>