简体   繁体   English

在React JS中,我正在尝试创建一个倒数计时器,但无法将第一秒变成一整秒

[英]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.

相关问题 倒数计时器js每1秒刷新一次 - Countdown timer js refresh every 1 second React:倒数计时器,如何每秒减少状态值? - React: Countdown timer, how to decrease a value in state every second? 我正在尝试在加载时运行两个函数,一个需要先运行,以便第二个可以填充框列表,但是,第二个没有得到数组 - I am trying to run two functions onLoad, one needs to run first so the second one can populate a boxlist, however, the second one doesn't get thearray 在 Html 中出现 blogspot 的下载按钮链接之前,如何制作 10 秒倒计时? - How can I make a 10 second countdown timer before a download button link appears for blogspot in Html? 倒数计时器在启动时会丢失一秒钟。 我怎样才能避免这种情况? - Countdown timer is losing a second when initiated. How can I avoid this? 如何在出现下载按钮链接之前设置 10 秒倒计时? - How can I make a 10 second countdown timer before a download button link appears? 我正在尝试使用async / await来获取服务,但是第二个服务返回并没有填充我的变量 - I'm trying to use async/await to get a service, but the second service returns don't fill my variables 我无法在按钮的第二次单击上使用第二个功能 - I can’t get the second function to work on the second click of the button 在第二次倒数后重设第一次倒数 - Reset first countdown after the second countdown 尝试使用 react js 创建一个多功能按钮 {在第一次点击时 - 保存数据,打开“查看”,然后在第二次点击时 - 导航到保存的页面} - Trying to create a multi-functional button using react js {on first click - saves data, turns “view”, and on second click - navigate to saved page}
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM