React ChessTimer

Simulate a Chess Timer

by vikikamath

HTML

<script src="https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xta1/t39.3284-6/12056959_1183410128340718_1702703460_n.js"></script>
<div id="main">

</div>

Babel + JSX

var ChessTimer = React.createClass({
  getInitialState: function() {
    return {wseconds: this.props.startWith || 0, bseconds: this.props.startWith || 0, color: 'WHITE', interval: undefined};
  },
  componentDidMount: function() {
    this.state.interval = setInterval.call(null, this.tick, 1000); 
  },
  tick: function() {
  	if(this.state.color === 'WHITE'){
    		
    		if (this.state.wseconds > 0){
        	this.setState({wseconds: this.state.wseconds - 1});
        } else{
        	clearInterval.call(null, this.state.interval);
        }
    } else{
    		if (this.state.bseconds > 0){
        	this.setState({bseconds: this.state.bseconds - 1});
        } else{
        	clearInterval.call(null, this.state.interval);
        }
    }
  },
  switch: function() {
  	clearInterval.call(null, this.state.interval);
    this.setState({color: this.state.color === 'WHITE' ? 'BLACK' : 'WHITE'});
    this.state.interval = setInterval.call(null, this.tick, 1000);
  },
  reset: function() {
  	clearInterval.call(null, this.state.interval);
  	this.setState({wseconds: this.props.startWith || 0, bseconds: this.props.startWith || 0, color: 'WHITE'});
    this.componentDidMount();
  },
  render: function() {
    return (
    	<div>
      <p>
        White has been running for {this.state.wseconds} seconds.
      </p>
      <p>
        Black has been running for {this.state.bseconds} seconds.
      </p>
      <button onClick={this.switch}>SWITCH</button>
      <button onClick={this.reset}>RESET</button>
      </div>
    );
  }
});

ReactDOM.render(
  <ChessTimer startWith={6} />,
  document.getElementById('main')
);