首页 > 解决方案 > 承诺中的 setInterval,在 React 中只执行一次

问题描述

我正在尝试创建一个倒数计时器,每秒滴答一秒。间隔只工作一次,不执行。问题是在进行服务器调用之前我没有this.state.timetill ,然后我可以开始计时器。因此,setInterval 函数必须隐藏在一个 Promise 中,它只执行一个。然而,timetill 变量可以是一个常量,一旦检索到它就不会改变。

componentDidMount = async () => {
const that = this;
*do stuff*
this.someFunction().finally(() => {
/*This right here, below is not working */
setInterval(that.createTimer(), 1000);  
});
}

我的 JSX 就是这样

{this.state.setTimer}

有问题的函数,时间必须除以 1000,因为 javascript 使用毫秒

createTimer = async timerNow => {
var timerNow = (await new Date().getTime()) / 1000;
// Find the distance between now and the count down date
var distance = this.state.timeTill - timerNow;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
//the variable displayed
var setTimer = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
this.setState({setTimer});
};

标签: reactjspromisesetinterval

解决方案


createTimer您传递to的返回值setInterval,而不是传递函数但不调用它

setInterval(this.createTimer, 1000)


推荐阅读