title: Handling a timer in React/Flux
body: <p>I'm working on an application where I want a timer to countdown from, say, 60 seconds to 0 and then change some content, after which the timer restarts again at 60.</p>
  
  <p>I have implemented this in React and Flux but since I'm new to this, I'm still running into some problems.</p>
  
  <p>I now want to add a start/stop button for the timer. I'm not sure where to put/handle the timer state.</p>
  
  <p>I have a component <code>Timer.jsx</code> which looks like this: </p>
  
  <pre><code>var React = require('react');
  var AppStore = require('../stores/app-store.js');
  var AppActions = require('../actions/app-actions.js');
  
  function getTimeLeft() {
    return {
      timeLeft: AppStore.getTimeLeft()
    }
  }
  
  var Timer = React.createClass({
    _tick: function() {
      this.setState({ timeLeft: this.state.timeLeft - 1 });
      if (this.state.timeLeft &lt; 0) {
        AppActions.changePattern();
        clearInterval(this.interval);
      }
    },
    _onChange: function() {
      this.setState(getTimeLeft());
      this.interval = setInterval(this._tick, 1000);
    },
    getInitialState: function() {
      return getTimeLeft();
    },
    componentWillMount: function() {
      AppStore.addChangeListener(this._onChange);
    },
    componentWillUnmount: function() {
      clearInterval(this.interval);
    },
    componentDidMount: function() {
      this.interval = setInterval(this._tick, 1000);
    },
    render: function() {
      return (
        &lt;small&gt;
          ({ this.state.timeLeft })
        &lt;/small&gt;
      )
    }
  });
  
  module.exports = Timer;
  </code></pre>
  
  <p>It retrieves a countdown duration from the store, where I simply have:</p>
  
  <p><code>var _timeLeft = 60;</code></p>
  
  <p>Now, when I want to implement a start/stop button, I feel like I should also implement this through Flux Actions, correct? So I was thinking of having something like this in my store:</p>
  
  <pre><code>dispatcherIndex: AppDispatcher.register(function(payload) {
    var action = payload.action;
  
    switch(action.actionType) {
      case AppConstants.START_TIMER:
        // do something
        break;
      case AppConstants.STOP_TIMER:
        // do something
        break;
      case AppConstants.CHANGE_PATTERN:
        _setPattern();
        break;
    }
  
    AppStore.emitChange();
  
    return true;
  })
  </code></pre>
  
  <p>However, since my Timer component currently handles the setInterval, I don't know how to get my START/STOP_TIMER events working. Should I move the setInterval stuff from the Timer component to the Store and somehow pass this down to my component?</p>
  
  <p>Full code can be found <a href="https://github.com/cabaret/caged-system-trainer">here</a>.</p>