[英]apply react setInterval, clearInterval useEffect
我正在嘗試使用 moment.jsx 每 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 並使用 useEffect 中的 setInteval 和 clearInterval 函數來計算剩余時間來創建計時器,但計時器不起作用。
為什么定時器 (setInteval, clearInterval) 不是每秒觸發一次? useOnlive Custom API Hook每秒調用一次,定時器是否起作用?
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
毫秒而不是1000
毫秒
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.