Last active
August 29, 2015 14:21
-
-
Save robhurring/dea2e85f4c6955405da1 to your computer and use it in GitHub Desktop.
Timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Timer extends React.Component { | |
constructor(props) { | |
super(props) | |
this._interval = null; | |
this.state = { | |
ticks: 0 | |
} | |
} | |
componentDidMount() { | |
if(this.props.seconds > 0) { | |
this.start() | |
} | |
} | |
componentWillUnmount() { | |
this.stop() | |
} | |
start() { | |
if(!this._interval) { | |
this._interval = setInterval(this.tick.bind(this), 1000) | |
} | |
} | |
stop() { | |
if(this._interval) { | |
this.pause() | |
this.reset() | |
} | |
} | |
pause() { | |
if(this._interval) { | |
clearInterval(this._interval) | |
this._interval = null; | |
} | |
} | |
reset() { | |
this.setState({ticks: 0}) | |
} | |
tick() { | |
var ticks = this.state.ticks + 1; | |
if(ticks > this.props.seconds) { | |
ticks = 0 | |
this.loop() | |
} | |
this.setState({ticks: ticks}) | |
} | |
percent() { | |
var ticks = this.state.ticks | |
var total = this.props.seconds | |
return (ticks / total) * 100; | |
} | |
loop() { | |
var onTick = this.props.onTick | |
if(onTick && typeof(onTick) === 'function') { | |
var resume = () => { | |
console.log(this); | |
this.start() | |
} | |
this.pause() | |
onTick(resume) | |
} | |
} | |
render() { | |
var width = 100 - this.percent(); | |
return ( | |
<div className="progress"> | |
<div | |
className="progress-bar progress-bar-striped" | |
role="progressbar" | |
style={{width: width + '%'}}> | |
</div> | |
</div> | |
) | |
} | |
} | |
Timer.defaultProps = { | |
seconds: 0, | |
onTick: function(){} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment