Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react'
- class Timer extends React.Component {
- constructor(props) {
- super(props)
- this.stopTime = Date.now() + (props.startTime * 1000)
- }
- state = {
- time: this.props.startTime * 10,
- }
- componentDidMount() {
- this.startCount()
- }
- componentWillReceiveProps(nextProps) {
- if (this.props.startTime !== nextProps.startTime) {
- this.stopTime = Date.now() + (nextProps.startTime * 1000)
- this.startCount()
- }
- }
- componentWillUnmount() {
- clearInterval(this.timer)
- }
- startCount = () => {
- this.timer = setInterval(this.stick, 1000)
- }
- stick = () => {
- const now = Date.now()
- if (this.stopTime - now <= 0) {
- this.setState(() => ({ time: 0 }))
- clearInterval(this.timer)
- } else {
- const time = Math.floor((this.stopTime - now) / 100)
- this.setState(() => ({ time }))
- }
- }
- render() {
- const { time } = this.state
- const seconds = Math.floor(time / 10)
- return <span>{seconds}</span>
- }
- }
- export default Timer
Add Comment
Please, Sign In to add comment