Skip to content

Instantly share code, notes, and snippets.

@robhurring robhurring/Timer.jsx
Last active Aug 29, 2015

Embed
What would you like to do?
Timer
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
You can’t perform that action at this time.