计时器
<template>
<div>
<h2>{{ time }}</h2>
<button @click="start">开始</button>
<button @click="stop">停止</button>
</div>
</template>
<script>
export default {
data() {
return {
time: "00:00:00",
timer: null,
seconds: 0,
minutes: 0,
hours: 0,
};
},
methods: {
start() {
this.timer = setInterval(() => {
this.seconds++;
if (this.seconds === 60) {
this.seconds = 0;
this.minutes++;
}
if (this.minutes === 60) {
this.minutes = 0;
this.hours++;
}
this.time = `${this.formatTime(this.hours)}:${this.formatTime(
this.minutes
)}:${this.formatTime(this.seconds)}`;
}, 1000);
},
stop() {
clearInterval(this.timer);
},
formatTime(time) {
return time < 10 ? `0${time}` : time;
},
},
};
</script>
倒计时
<template>
<div>
<h2>{{ time }}</h2>
<button @click="start">开始</button>
<button @click="stop">停止</button>
</div>
</template>
<script>
export default {
data() {
return {
time: "00:00:00",
timer: null,
remainingTime: 0,
};
},
methods: {
start() {
const endTime = Date.now() + this.remainingTime;
this.timer = setInterval(() => {
const remainingTime = endTime - Date.now();
if (remainingTime <= 0) {
clearInterval(this.timer);
this.time = "00:00:00";
} else {
const hours = Math.floor(remainingTime / 3600000);
const minutes = Math.floor((remainingTime % 3600000) / 60000);
const seconds = Math.floor((remainingTime % 60000) / 1000);
this.time = `${this.formatTime(hours)}:${this.formatTime(
minutes
)}:${this.formatTime(seconds)}`;
}
}, 1000);
},
stop() {
clearInterval(this.timer);
},
formatTime(time) {
return time < 10 ? `0${time}` : time;
},
},
};
</script>
这个倒计时会根据剩余时间来更新时间显示,包括小时、分钟和秒,可以通过“开始”和“停止”按钮控制倒计时的启停。倒计时的实现依赖于Vue组件的状态和计时器函数的调用,通过定时器setInterval()来实现倒计时的功能,计算剩余时间来更新倒计时的显示。