all files / src/components/ Timer.jsx

97.3% Statements 36/37
70% Branches 14/20
100% Functions 7/7
97.22% Lines 35/36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75                                       11×                                          
import React from 'react';
import PropTypes from 'prop-types';
import { now, fDuration } from '../modules/dates';
 
const propTypes = {
  endTime: PropTypes.number,
  isRunning: PropTypes.bool.isRequired,
  startTime: PropTypes.number,
  status: PropTypes.string,
  style: PropTypes.object,
};
 
const defaultProps = {
  endTime: null,
  startTime: null,
  status: 'success',
  style: null,
};
 
export default class Timer extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      clockStr: '',
    };
    this.stopwatch = this.stopwatch.bind(this);
  }
  componentWillMount() {
    this.startTimer();
  }
  componentWillUnmount() {
    this.stopTimer();
  }
  startTimer() {
    if (!this.timer) {
      this.timer = setInterval(this.stopwatch, 30);
    }
  }
  stopTimer() {
    this.timer = clearInterval(this.timer);
  }
  stopwatch() {
    if (Ethis.props && this.props.startTime) {
      const endDttm = this.props.endTime || now();
      if (Ethis.props.startTime < endDttm) {
        const clockStr = fDuration(this.props.startTime, endDttm);
        this.setState({ clockStr });
      }
      if (I!this.props.isRunning) {
        this.stopTimer();
      }
    }
  }
  render() {
    if (Ethis.props && this.props.isRunning) {
      this.startTimer();
    }
    let timerSpan = null;
    if (Ethis.props) {
      timerSpan = (
        <span
          className={`inlineBlock m-r-5 label label-${this.props.status}`}
          style={this.props.style}
        >
          {this.state.clockStr}
        </span>
      );
    }
    return timerSpan;
  }
}
 
Timer.propTypes = propTypes;
Timer.defaultProps = defaultProps;