[英]In React JS I'm trying to create a countdown timer but can't get the first second to be a full second
I'm using setInterval with 1000ms intervals inside componentDidMount which means that depending on when the user hits the submit button to enter the time to count down from, the first second on the countdown could take anywhere from 1ms to 1000ms. 我在componentDidMount内部使用间隔为1000毫秒的setInterval,这意味着,取决于用户何时按下提交按钮输入倒数时间,倒数的第一秒可能需要1毫秒至1000毫秒。 Here is the code in question:
这是有问题的代码:
minusOne() {
if(this.state.time > 0){
this.setState({time: this.state.time -1});
}
}
componentDidMount(){
setInterval(() => this.minusOne(), 1000);
}
Any ideas on how to get that first second to always take 1000ms? 关于如何使第一秒始终花费1000ms的任何想法? Thanks
谢谢
Just launch your interval on button hit instead of componentDidMount
. 只需按一下按钮击中间隔而不是
componentDidMount
。
onSubmit() {
...
// remove any previous interval (noop for undefined handle)
clearInterval(this.state.countdownIntervalHandle);
this.setState({countdownIntervalHandle: setInterval(...)});
}
Don't forget to add clearInterval
to componentWillUnmount
if necessary. 必要时不要忘记将
clearInterval
添加到componentWillUnmount
。
Use setTimeout to force the countdown at 1000ms. 使用setTimeout将倒计时强制为1000ms。
componentDidMount(){
setTimeout( setInterval( () => this.minusOne(), 1000), 1000);
};
wonkledge wonkledge
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.