百度查了很多实现计时器的方法,这种方式实现计时器是比较稳定的好的方式。
原作者博客地址:https://blog.csdn.net/qq_40146789/article/details/109357665?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-7.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-7.control
<template> <div id="app">开始时间:{{ start_time }} 用时:{{ count_time }}</div> </template> <script> export default { name: ‘App‘, data() { return { start_time: ‘2021-07-19 14:00:00‘, count_time: ‘00:00:00‘ } }, mounted() { this.countTime(this.start_time) }, beforeDestroy() { if (this.timer) { clearInterval(this.timer) } }, methods: { // 计算用时 startTime为开始时间 字符串格式‘2020-10-29 14:00:00’或者Date格式都可以 countTime(startTime) { if (!startTime) return let start_time = new Date(startTime) let _this = this this.timer = setInterval(() => { let millisecond = new Date() - start_time let h = Math.floor(millisecond / (60 * 60 * 1000)) h = h < 10 ? ‘0‘ + h : h let min = Math.floor((millisecond % (60 * 60 * 1000)) / (60 * 1000)) min = min < 10 ? ‘0‘ + min : min let sec = Math.floor(((millisecond % (60 * 60 * 1000)) % (60 * 1000)) / 1000) sec = sec < 10 ? ‘0‘ + sec : sec _this.count_time = h + ‘:‘ + min + ‘:‘ + sec }, 1000) } } } </script>