我曾见过很多JavaScript倒计时器,并想要在React中让一个工作。
我借用了我在网上找到的这个函数:
secondsToTime(secs){
let hours = Math.floor(secs / (60 * 60));
let divisor_for_minutes = secs % (60 * 60);
let minutes = Math.floor(divisor_for_minutes / 60);
let divisor_for_seconds = divisor_for_minutes % 60;
let seconds = Math.ceil(divisor_for_seconds);
let obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
};
然后我自己编写了这段代码
initiateTimer = () => {
let timeLeftVar = this.secondsToTime(60);
this.setState({ timeLeft: timeLeftVar })
};
startTimer = () => {
let interval = setInterval(this.timer, 1000);
this.setState({ interval: interval });
};
timer = () => {
if (this.state.timeLeft >0){
this.setState({ timeLeft: this.state.timeLeft -1 });
}
else {
clearInterval(this.state.interval);
//this.postToSlack();
}
};
当前,点击时屏幕上会显示时间: 剩余时间:1分钟: 0秒
。
但它没有把它减少到剩余时间:0分钟:59秒
,然后是剩余时间:0分钟:58秒
等等。
我想我需要使用不同的参数再次调用该函数。我该如何实现?
编辑:我忘记说了,我希望能够将秒转换为分钟和秒