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>

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

相关推荐
y***86697 小时前
TypeScript在Electron应用中的使用
javascript·typescript·electron
zy happy9 小时前
若依 vue3 报错:找不到模块“@/api/xxxx/xxxxx”或其相应的类型声明。。Vue 3 can not find mod
前端·javascript·vue.js
meichaoWen10 小时前
【Vue3】vue3的全面学习(一)
前端·javascript·学习
b***748811 小时前
Vue开源
前端·javascript·vue.js
ByteCraze13 小时前
我整理的大文件上传方案设计
前端·javascript
前端小白۞13 小时前
vue2 md文件预览和下载
前端·javascript·vue.js
5***790014 小时前
Vue项目性能优化
前端·javascript·vue.js
丫丫72373414 小时前
Three.js 模型树结构与节点查询学习笔记
javascript·webgl
车传新15 小时前
Javascript
javascript
天若有情67315 小时前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise