Skip to content

Instantly share code, notes, and snippets.

@azat-co
Created May 22, 2017 20:16
Show Gist options
  • Save azat-co/a85c1f9e258d410abffb79c2dff987d2 to your computer and use it in GitHub Desktop.
Save azat-co/a85c1f9e258d410abffb79c2dff987d2 to your computer and use it in GitHub Desktop.
const ReactDOM = require('react-dom')
const React = require('react')
const TimerButton = (props) => {
return (
<button type="button" onClick={()=>{
props.handler(props.time)
}}>Start {props.time}</button>
)
}
const TimerLabel = (props) => {
return <div>{props.timeLeft}</div>
}
class TimerWrapper extends React.Component {
constructor(props) {
super(props)
this.startTimer = this.startTimer.bind(this)
this.state = {timeLeft: 0, intervalRef: null}
}
startTimer(timePeriod) {
clearInterval(this.state.intervalRef)
let intervalRef = setInterval(()=>{
if (this.state.timeLeft == 0 ) return clearInterval(this.state.intervalRef)
this.setState({timeLeft: --this.state.timeLeft})
}, 1000)
this.setState({intervalRef: intervalRef, timeLeft: timePeriod})
}
render() {
return (
<div>
<TimerButton time="5" handler={this.startTimer}/>
<TimerButton time="10" handler={this.startTimer}/>
<TimerButton time="15" handler={this.startTimer}/>
<TimerLabel timeLeft={this.state.timeLeft}/>
</div>
)
}
}
ReactDOM.render(
<TimerWrapper/>,
document.getElementById('timer')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment