简体   繁体   中英

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,...)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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