round-timer.component.jsx 979 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import React from "react";
  2. import ms from "pretty-ms";
  3. class RoundTimer extends React.Component {
  4. constructor(props) {
  5. super(props);
  6. const { seconds } = this.props;
  7. this.state = {
  8. running: false,
  9. remaining: seconds,
  10. }
  11. }
  12. componentDidMount() {
  13. this.timer = setInterval(() => this.countDown(), 1000);
  14. }
  15. componentWillUnmount() {
  16. clearInterval(this.timer);
  17. }
  18. countDown() {
  19. const { remaining } = this.state;
  20. this.setState({ remaining: remaining - 1 });
  21. if (remaining <= 0) {
  22. const { onTimeout } = this.props;
  23. clearInterval(this.timer);
  24. onTimeout();
  25. }
  26. }
  27. render() {
  28. const { remaining } = this.state;
  29. const { style } = this.props;
  30. return (
  31. <div style={{ display: "flex", justifyContent: "center", alignItems: "center", ...style }}>
  32. {remaining > 0 ? <p>Time: {ms(remaining * 1000)}</p> : <p>Time's up!</p>}
  33. </div>
  34. );
  35. }
  36. }
  37. export default RoundTimer;