示例代码如下:
<template>
<div class="counter-timer-row">
<span>{{ cTime }}</span>
</div>
</template>
<script>
export default {
name: "counterTimer",
components: {},
data() {
return {
cTime: "00:00",
};
},
created() {
this.startTimer();
},
methods: {
startTimer() {
let that = this;
let lastTime = new Date().getTime();
this.myTimer=setInterval(function () {
//setInterval定时方法,每一秒执行一次,实现时钟效果
let cTime=new Date().getTime()
let xcTime=cTime-lastTime
let rTime = that.formatDuring(xcTime);
console.log('rTime',rTime)
that.cTime=rTime
//至此,时间输出为11:05:03正确格式,而非11:5:3
}, 1000);
},
formatDuring(mss) {
var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
var seconds = (mss % (1000 * 60)) / 1000;
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
},
//停止timer
stopTimer(){
if(!!this.myTimer){
clearInterval(this.myTimer)
}
}
},
};
</script>
<style scoped="scoped">
.counter-timer-row {
display: flex;
flex-direction: row;
justify-content: center;
}
</style>
网友评论