简体   繁体   English

如何停止计时器?

[英]How do I stop this timer?

I have this app that is basically just a very simple timer. 我有这个程序,基本上只是一个非常简单的计时器。 The problem is I don't know how to freeze it when the user presses "PAUSE". 问题是当用户按下“暂停”时,我不知道如何冻结它。 The function pad2 just format numbers so they are two-digit numbers (eg 01, 02,...) 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
}

I believe that the concept of pausing will have to be translated into stop, with the capacity to start again. 我认为,暂停的概念必须转化为停止,并具有重新开始的能力。

So, you would clearInterval upon pause, and then create a new setInterval having kept track of the minutes and seconds when it was paused so as to continue to increment the time elapsed. 因此,您将在暂停时清除InterInterval,然后创建一个新的setInterval来跟踪暂停时的分钟和秒,以便继续增加经过的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM