簡體   English   中英

如何停止計時器?

[英]How do I stop this timer?

我有這個程序,基本上只是一個非常簡單的計時器。 問題是當用戶按下“暫停”時,我不知道如何凍結它。 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
}

我認為,暫停的概念必須轉化為停止,並具有重新開始的能力。

因此,您將在暫停時清除InterInterval,然后創建一個新的setInterval來跟蹤暫停時的分鍾和秒,以便繼續增加經過的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM