我试图在JSX中使用moment每1秒计时一次。
const onlive = useOnlive(); // react-query Custom Hook
console.log(onlive);
{
"event": {
"id": 933,
"startDate": "2023-01-17T01:00:00.000Z"
},
"nextEvent": {
"id": 930,
"startDate": "2023-01-18T13:20:00.000Z"
}
}
我试图通过计算nextEvent - currentTime和使用setinterval和clearInterval函数在useEffect中计算剩余时间来创建一个计时器,定时器不工作
为什么定时器(setinterval, clearInterval)不是每秒触发一次?当useOnlive自定义API钩子每秒被调用时,计时器工作吗?
const nextStartTime = moment(onlive.data?.nextEvent?.startDate); // 2023-01-18
const nowTime = moment(); // current time
useEffect(() => {
const nextStartTimeId = setInterval(() => {
setHour(nextStartTime.diff(nowTime, 'hours', false) % 24);
setMinute(nextStartTime.diff(nowTime, 'minutes', false) % 60);
setSecond(nextStartTime.diff(nowTime, 'seconds', false) % 60);
}, 100);
return () => clearInterval(nextStartTimeId);
}, [setHour, setMinute, setSecond, nextStartTime, nowTime]);
return (
<span>
The session starts {hour < 10 ? "0" + hour : hour}:
{minute < 10 ? "0" + minute : minute}:
{second < 10 ? "0" + second : second} later.
</span>
)
如何使定时器工作?
您将间隔设置为100
ms代替1000
ms
const nextStartTimeId = setInterval(() => {
setHour(nextStartTime.diff(nowTime, "hours", false) % 24);
setMinute(nextStartTime.diff(nowTime, "minutes", false) % 60);
setSecond(nextStartTime.diff(nowTime, "seconds", false) % 60);
}, 1000);