页面倒计时,后端传入开始时间及duration
- 应用场景:如果前端实现计时功能,可以F12直接修改,所以利用后端传入的数据计算
- 代码:
const [time, setTime] = useState(999)
const timeDown = useRef(999)
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()
return () => clearInterval(countdownTimer.current)
}, [])
useEffect(() => {
if (time <= 0) {
end()
notification.open({
message: '考试结束通知',
description: '考试时长已结束,现为您结束本场笔试',
duration: 0,
})
}
}, [time])
const updateTime = () => {
return dayjs().hour(0).minute(0).second(time).format('HH:mm:ss')
}
<div className={style.time}>
<FieldTimeOutlined />
<span>{updateTime()}</span>
</div>
- 理解:
- 用到setInterval,就要在useEffect里返回时清除clearInterval
- 注意判别每一次传进来的时间及时间差。每次进入duration变小,startTime可能和当前时间差值大于duration
- useRef useState用法
上篇笔记useRef和useState