页面倒计时做法,后端传入开始时间及duration

页面倒计时,后端传入开始时间及duration

  1. 应用场景:如果前端实现计时功能,可以F12直接修改,所以利用后端传入的数据计算
  2. 代码:
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()
    // interval记得清空
    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>
  1. 理解:
  • 用到setInterval,就要在useEffect里返回时清除clearInterval
  • 注意判别每一次传进来的时间及时间差。每次进入duration变小,startTime可能和当前时间差值大于duration
  • useRef useState用法
    上篇笔记useRef和useState
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值