<template>
<div>
{{nowTime}}
<button @click="getNowTime">开始计时</button>
<button @click="stopTiming">停止计时</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const nowTime = ref("00:00:00")
let timer: any
let timerStop = false
const getNowTime =()=>{
if (timer) {
clearTimeout(timer)
timer = null
}
if (timerStop) {
return
}
const now = new Date();
const hour=now.getHours()<10?"0" + now.getHours():now.getHours();
const minu=now.getMinutes()<10?"0" + now.getMinutes():now.getMinutes();
const sec=now.getSeconds()<10?"0" + now.getSeconds():now.getSeconds()
nowTime.value = hour+":"+ minu +":"+sec;
timer = setTimeout(getNowTime,1000)
}
const stopTiming = ()=>{
f (timer) {
clearTimeout(timer)
timer = null
}
timerStop = true
}
</script>
为什么要用timeout代替interval,这篇文章写的还不错,可以看下