Stopwatch.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import React, { Component } from "react";
  2. import { Button, Container } from "react-bootstrap";
  3. export default class Stopwatch extends Component {
  4. constructor(props) {
  5. super(props);
  6. this.state = {
  7. digit: 0,
  8. color: "#111",
  9. isDisabled: false,
  10. };
  11. }
  12. handleStart() {
  13. this.setState(() => ({ isDisabled: true }));
  14. this.timerID = setInterval(() => this.tick(), 1000);
  15. }
  16. tick() {
  17. this.setState((state) => ({
  18. digit: state.digit + 1,
  19. color: "#" + Math.floor(Math.random() * 16777215).toString(16),
  20. }));
  21. }
  22. handleStop() {
  23. this.setState(() => ({ isDisabled: false }));
  24. clearInterval(this.timerID);
  25. }
  26. handleReset() {
  27. this.setState({ digit: 0, color: "#111" });
  28. }
  29. render() {
  30. return (
  31. <>
  32. <h1
  33. style={{
  34. textAlign: "center",
  35. margin: "20px 0",
  36. color: this.state.color,
  37. }}
  38. >
  39. {this.state.digit}
  40. </h1>
  41. <Container style={{ textAlign: "center" }}>
  42. <Button
  43. variant="success"
  44. disabled={this.state.isDisabled}
  45. onClick={() => this.handleStart()}
  46. >
  47. Start
  48. </Button>{" "}
  49. <Button
  50. variant="danger"
  51. disabled={!this.state.isDisabled}
  52. onClick={() => this.handleStop()}
  53. >
  54. Stop
  55. </Button>{" "}
  56. <Button
  57. variant="warning"
  58. disabled={this.state.isDisabled}
  59. onClick={() => this.handleReset()}
  60. >
  61. Reset
  62. </Button>{" "}
  63. </Container>
  64. </>
  65. );
  66. }
  67. }