javascript - 如何停止此计时器?
问题描述
我有这个应用程序,它基本上只是一个非常简单的计时器。问题是当用户按下“暂停”时我不知道如何冻结它。该函数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
}
解决方案
我相信暂停的概念必须转化为停止,并具有重新开始的能力。
因此,您将在暂停时清除Interval,然后创建一个新的 setInterval 并跟踪暂停时的分钟和秒数,以便继续增加经过的时间。
推荐阅读
- java - 以编程方式为给定类型的每个 bean/configuration/... 创建 spring bean
- asp.net-mvc - html.TextAreaFor 和 HtmlDecode
- flutter - 在 Flutter 的 for 循环中生成的 2 个文本小部件之间画线
- c - C中的函数jalr
- botframework - 非 ngrok 的 MS Teams 机器人端点地址
- python - Selenium Python - 无法选择选项选择框
- pandas - Excel 单元格包含标题及其值,以 : 分隔。想在熊猫中创建数据框创建标题并从单元格中填充其值
- regex - Unexpected Behavior of Regex in Perl with Lookahead/Lookbehind
- python - How to create a row rdd from a list in pyspark
- elasticsearch - Elasticsearch IO slow, duplicate reads with Google Cloud Dataflow