柚子快報激活碼778899分享:前端 頁面倒計時做法,后端計時
柚子快報激活碼778899分享:前端 頁面倒計時做法,后端計時
頁面倒計時,后端傳入開始時間及duration
應(yīng)用場景:如果前端實現(xiàn)計時功能,可以F12直接修改,所以利用后端傳入的數(shù)據(jù)計算代碼:
const [time, setTime] = useState(999)
const timeDown = useRef(999)
// 在頁面初始化調(diào)接口獲得參數(shù)的函數(shù)里做計時操作:
// 初始獲取試卷
const getFileList = async () => {
if (!res.duration) {
end()
return
}
let dtime = 0
if (!res.startTime) {
dtime = Number(res.duration) * 60
} else {
dtime = Number(res.duration) * 60 - Math.abs(dayjs(res.startTime).diff(dayjs())) / 1000
}
setTime(dtime)
timeDown.current = dtime
countdownTimer.current = setInterval(() => {
timeDown.current--
setTime(timeDown.current)
}, 1000)
}
useEffect(() => {
getFileList()
// interval記得清空
return () => clearInterval(countdownTimer.current)
}, [])
// 倒計時
useEffect(() => {
if (time <= 0) {
end()
notification.open({
message: '考試結(jié)束通知',
description: '考試時長已結(jié)束,現(xiàn)為您結(jié)束本場筆試',
duration: 0,
})
}
}, [time])
const updateTime = () => {
return dayjs().hour(0).minute(0).second(time).format('HH:mm:ss')
}
// 頁面顯示
{updateTime()}
理解:
用到setInterval,就要在useEffect里返回時清除clearInterval注意判別每一次傳進來的時間及時間差。每次進入duration變小,startTime可能和當(dāng)前時間差值大于durationuseRef useState用法 上篇筆記useRef和useState
柚子快報激活碼778899分享:前端 頁面倒計時做法,后端計時
相關(guān)鏈接
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。