gpt4 book ai didi

javascript - 如果满足条件可以清除setInterval吗?不使用 componentDidMount?

转载 作者:行者123 更新时间:2023-12-02 21:14:50 24 4
gpt4 key购买 nike

我正在创建一个简单的计时器。我希望计时器在每次达到 00 秒时重置。我正在使用 setInterval 但它不会在 this.state.seconds 中每次值为 0 时清除。我见过一些使用 componentDidMount 和 componentDidUnmount 的解决方案,但有兴趣从调用 setInterval 本身的方法中执行和清除 setInterval 。这是可以做的事情吗?

到目前为止,即使在 0 秒后,计时器也会继续减少。这是我的 codepen 草稿:https://codepen.io/tonytony92/pen/bGdJeRg

class MyApp extends React.Component {
constructor(props) {
super(props)
this.state = {
minutes: 25,
seconds: 59,
play: false,
display: "SESSION"
}
this.handlePlay = this.handlePlay.bind(this)
}


handlePlay() {
let func1 = () => {
this.setState({
seconds: this.state.seconds - 1
})
console.log(this.state.seconds)
}

if (this.state.seconds > 0) {
this.Myvar = setInterval(() => {
console.log(this.state.seconds)
this.setState({
seconds: this.state.seconds - 1
})
}, 200)
}
else {
console.log("minus")
clearInterval(this.Myvar) /// not clearing ///
}
}
}

最佳答案

handlePlay 在单击按钮时启动计时器,但不会按照您的预期检查剩余时间。

这是因为提供给setInterval的函数是

console.log(this.state.seconds)
this.setState({
seconds: this.state.seconds - 1
})

而不是函数handlePlay

为了更好的可读性和可维护性(并且还有代码可以工作),请将处理时间减少的逻辑与启动计时器的代码分开。像这样:

class MyApp extends React.Component {
constructor(props) {
super(props)
this.state = {
minutes: 0,
seconds: 10,
play: false,
display: "SESSION"
}
this.handlePlay = this.handlePlay.bind(this);
this.handleTime = this.handleTime.bind(this);
}

// handlePlay only launches the timer.
handlePlay() {
this.Myvar = setInterval(this.handleTime, 200);
}

// handleTime deals with the logic of decrementing time.
handleTime() {
if (this.state.seconds > 0) {
console.log(this.state.seconds)
this.setState({
seconds: this.state.seconds - 1
})
} else {
console.log("minus")
clearInterval(this.Myvar)
}
}
}

handlePlay 现在是 UI(按钮单击)和逻辑(处理时间减少)之间的接口(interface)。它仅使用 setInterval 启动计时器。

handleTime 处理时间减少的逻辑。每次 setInterval 触发时都会调用它,并在时间结束后停止计时器。

关于javascript - 如果满足条件可以清除setInterval吗?不使用 componentDidMount?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60998261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com