Skip to content

Instantly share code, notes, and snippets.

@gHashTag
Created April 12, 2017 05:03
Show Gist options
  • Save gHashTag/5a3f1295c4796da29846e9acacc11342 to your computer and use it in GitHub Desktop.
Save gHashTag/5a3f1295c4796da29846e9acacc11342 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
import {
Text,
Button,
StyleSheet,
View
} from 'react-native'
class TimerThing extends Component {
constructor(props) {
super(props)
this.state = {
on: false,
time: 0
}
this.timerId = 0
this.lastUpdateTime = 0
}
componentWillMount() {
//this.startTimer()
}
componentWillUnmount() {
this.clearTimer()
}
update() {
const now = Date.now()
const delta = now - this.lastUpdateTime
this.lastUpdateTime = now
this.setState({time: this.state.time += delta})
}
startTimer() {
this.setState({on: true})
this.lastUpdateTime = Date.now()
this.timerId = setInterval(() => {
this.update()
}, 500)
}
pauseTimer() {
this.setState({on: false})
this.clearTimer()
}
clearTimer() {
clearInterval(this.timerId)
}
formatTime(time) {
const secs = Math.floor(time / 1000)
const s = secs % 60
const m = Math.floor(secs / 60) % 60
const ss = s < 10 ? `0${s}` : `${s}`
const mm = m < 10 ? `0${m}` : `${m}`
return `${mm}:${ss}`
}
onButtonPress() {
this.state.on ? this.pauseTimer() : this.startTimer()
}
render() {
const title = this.state.on ? "Pause" : "Run"
const time = this.formatTime(this.state.time)
return(
<View>
<Text style={styles.timer}>{time}
</Text>
<Button title={title}
onPress={this.onButtonPress.bind(this)}
/>
</View>
)
}
}
export default TimerThing
const styles = StyleSheet.create({
container: {
},
timer: {
fontSize: 40,
fontWeight: 'bold',
textAlign: 'center'
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment