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 天前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
阿蒙Amon1 天前
JavaScript学习笔记:6.表达式和运算符
javascript·笔记·学习
小a杰.1 天前
Flutter 设计系统构建指南
开发语言·javascript·ecmascript
kgduu1 天前
js之事件系统
javascript
前端老宋Running1 天前
“受控组件”的诅咒:为什么你需要 React Hook Form + Zod 来拯救你的键盘?
前端·javascript·react.js
阿蒙Amon1 天前
JavaScript学习笔记:7.数字和字符串
javascript·笔记·学习
Highcharts.js1 天前
官方文档|Angular 框架集成 Highcharts Dashboards
前端·javascript·angular.js·highcharts·看板·使用文档·dashboards
韭菜炒大葱1 天前
React 新手村通关指南:状态、组件与魔法 UI 🧙‍♂️
前端·javascript·react.js
小明记账簿1 天前
JavaScript浮点数精度问题及解决方案
开发语言·javascript·ecmascript
1024肥宅1 天前
JavaScript性能与优化:手写实现关键优化技术
前端·javascript·面试