我该如何停止这个计时器?

时间:2018-06-10 13:47:45

标签: javascript react-native

我有这个应用程序基本上只是一个非常简单的计时器。问题是,当用户按下" PAUSE"时,我不知道如何冻结它。函数pad2只是格式化数字,因此它们是两位数字(例如01,02,...)

import React from 'react';
import { StyleSheet, Text, TextInput, View, Switch, Button } from 'react- 
native';
import { vibrate } from './utils'


export default class App extends React.Component {
  constructor() {
  super()
this.buttonOnPress = this.buttonOnPress.bind(this)
this.state = {
  mins: 0,
  secs: 0,
  buttonValue: "START"
}
}


  triggerTimer = () => {
    this.interval = setInterval(this.inc, 1000)
}


componentWillUnmount() {
  clearInterval(this.interval)
}


inc = () => {
  this.setState(prevState => ({
    secs: prevState.secs + 1,
}))
if (this.state.secs === 59) {
  setTimeout(() => this.setState({
    secs: 0,
  }), 1000)
  setTimeout(() => this.setState(prevState => ({
    mins: prevState.mins + 1,
  })), 1000)
}
}


buttonOnPress() {
this.triggerTimer()
this.setState({
  buttonValue: "PAUSE"
})
if (this.state.buttonValue === "PAUSE") {
  this.setState({
    buttonValue: "START"
  })
}
}


render() {
return (
  <View style={styles.container}>
    <Text style={styles.text}>
      "{pad2(this.state.mins)}:{pad2(this.state.secs)}"
      </Text>
    <Button onPress={this.buttonOnPress} title={this.state.buttonValue} />
  </View>
)
}
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    fontSize: 48,
  },
  input: {
    flex: 2,
  }
});

function pad2(number) {
  return (number < 10 ? '0' : '') + number
}

1 个答案:

答案 0 :(得分:0)

我相信暂停的概念必须转化为停止,并有能力重新开始。

因此,您可以在暂停时使用clearInterval,然后创建一个新的setInterval,它会跟踪暂停时的分钟和秒数,以便继续增加经过的时间。

相关问题