Guest User

Untitled

a guest
May 23rd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. import React from 'react'
  2.  
  3. class Timer extends React.Component {
  4. constructor(props) {
  5. super(props)
  6. this.stopTime = Date.now() + (props.startTime * 1000)
  7. }
  8.  
  9. state = {
  10. time: this.props.startTime * 10,
  11. }
  12.  
  13. componentDidMount() {
  14. this.startCount()
  15. }
  16.  
  17. componentWillReceiveProps(nextProps) {
  18. if (this.props.startTime !== nextProps.startTime) {
  19. this.stopTime = Date.now() + (nextProps.startTime * 1000)
  20. this.startCount()
  21. }
  22. }
  23.  
  24. componentWillUnmount() {
  25. clearInterval(this.timer)
  26. }
  27.  
  28. startCount = () => {
  29. this.timer = setInterval(this.stick, 1000)
  30. }
  31.  
  32. stick = () => {
  33. const now = Date.now()
  34. if (this.stopTime - now <= 0) {
  35. this.setState(() => ({ time: 0 }))
  36. clearInterval(this.timer)
  37. } else {
  38. const time = Math.floor((this.stopTime - now) / 100)
  39. this.setState(() => ({ time }))
  40. }
  41. }
  42.  
  43. render() {
  44. const { time } = this.state
  45. const seconds = Math.floor(time / 10)
  46. return <span>{seconds}</span>
  47. }
  48. }
  49.  
  50. export default Timer
Add Comment
Please, Sign In to add comment