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>

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

相关推荐
百度一下吧20 小时前
umi后台管理项目实战:从工程搭建到生产构建
java·前端·javascript
haerapi20 小时前
仓库拣货路线不只靠最短边:S 形启发式的反例记录
android·开发语言·javascript
事圆则缓20 小时前
Flutter 状态管理框架对比(六):同一个购物车,四种方案怎么落地?
前端·javascript·flutter
5008420 小时前
React Native for OpenHarmony 实战:三方库 react-native-torch 的鸿蒙化适配指南
javascript·react native·react.js·harmonyos
500841 天前
React Native for OpenHarmony 实战:三方库 react-native-device-uptime 的鸿蒙化适配指南
javascript·分布式·react native·react.js·harmonyos
admin and root1 天前
「AI安全篇」实战AntiDebug自动化JS逆向加解密MCP
javascript·人工智能·网络安全·自动化·漏洞挖掘·cnvd·src赏金
wengad1 天前
从 wangEditor 迁到 wangEditor-next
前端·javascript·vue.js
行者-全栈开发1 天前
【前端/JS框架】CVE-2026-3854:GitHub Enterprise Server X-Stat注入XSS漏洞深度剖析与紧急修复指南
前端·javascript·github
怕浪猫1 天前
2026年金九银十,我面了22个前端
前端·javascript·面试
前端的日常1 天前
一个人+AI做情侣食谱小程序,30天纯赚
前端·javascript·后端