Vue3动态时间显示

首先来看一下setInterval()和clearInterval()的使用以及注意事项

setInterval(func, millisec) id_interval : 间隔指定的毫秒数不停地执行指定的代码,定时器

  • 两个参数都是必须的,第一个参数为要调用的函数或要执行的代码串。第二个参数为周期性执行或调用 code 之间的时间间隔,以毫秒计。
  • 返回值为定时器的 Id

clearInterval(id_of_setinterval) : 用于停止 setInterval() 方法执行的函数代码

  • 参数是必须的,为setInterval返回的ID值

动态时间显示案例

javascript 复制代码
<template>
  <div>{{ curTime }}</div>
</template>

<script setup>
// 定时器:1s刷新一次时间
let timer = null

const getDeviceCurTime = _.throttle(() => {
  LoadingRequestUtil(getCurTime()).do(result => {
    if (result.success) {
      const serverTimeStr = result.data.time
      updateClock(new Date(serverTimeStr))
    }
  })
}, 100)

// 每1秒更新一次时钟
const updateClock = (serverTime) => {
  curTime.value = serverTime.toLocaleString()
  if (timer !== null) {
    // 清除定时器,避免计时器循环调用卡死崩溃
    clearInterval(timer)
    timer = null
  }
  timer = setInterval(() => {
    serverTime.setSeconds(serverTime.getSeconds() + 1)
    curTime.value = serverTime.toLocaleString()
  }, 1000)
}

onMounted(() => {
  onRefresh()
  getTimeZoneInfoList()
})

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

事实上,这种动态时间显示相比真是服务器的时间多了一部分代码执行的时间,所以随着时间的推移,前端显示的时间会比服务器的时间小了不少。

相关推荐
Asize19 小时前
HTTP 明明无状态,登录态怎么就保住了——React + Zustand + JWT 鉴权全流程拆解
前端·javascript
爱酱丶20 小时前
VS Code 快速生成Vue3 + TypeScript + Setup 基础空模板
前端·javascript·typescript
Maxkim20 小时前
在 GitHub 仓库里配一个 AI Code Reviewer,自动审查 PR
前端·javascript
NeverSettle_20 小时前
Agent 如何快速调用公司接口?——CLI + Skill 实践与踩坑
前端·javascript·后端
sugar__salt21 小时前
三列布局与 TypeScript 工具类型 Pick / Omit / Partial 详解
前端·javascript·typescript
名字还没想好☜21 小时前
Next.js Route Handler 做 SSE 服务端推送:实时进度条、自动重连与什么时候别用 WebSocket
开发语言·javascript·websocket·react·sse·next.js
IMPYLH21 小时前
HTML 的 <html> 元素
前端·javascript·html
To_OC1 天前
LC 239 滑动窗口最大值:从暴力超时到单调队列一遍过
javascript·算法·leetcode
Mh1 天前
虚拟滚动真的比普通滚动性能更好吗?
前端·javascript·性能优化
kyriewen1 天前
我把 AI 写的并发请求控制器手写了一遍——3 个语义我当时根本讲不清
前端·javascript·面试