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