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>

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

相关推荐
一 乐1 天前
婚纱摄影网站|基于ssm + vue婚纱摄影网站系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·spring boot·后端
xkxnq1 天前
第二阶段:Vue 组件化开发(第 16天)
前端·javascript·vue.js
Van_Moonlight1 天前
RN for OpenHarmony 实战 TodoList 项目:空状态占位图
javascript·开源·harmonyos
xkxnq1 天前
第一阶段:Vue 基础入门(第 15天)
前端·javascript·vue.js
BBBBBAAAAAi1 天前
Claude Code安装记录
开发语言·前端·javascript
源码获取_wx:Fegn08951 天前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
Jing_Rainbow1 天前
【 前端三剑客-37 /Lesson61(2025-12-09)】JavaScript 内存机制与执行原理详解🧠
前端·javascript·程序员
UIUV1 天前
模块化CSS学习笔记:从作用域问题到实战解决方案
前端·javascript·react.js
Kakarotto1 天前
使用ThreeJS绘制东方明珠塔模型
前端·javascript·vue.js
donecoding1 天前
TypeScript `satisfies` 的核心价值:两个例子讲清楚
前端·javascript