vue计时器代码和倒计时代码

计时器

<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()来实现倒计时的功能,计算剩余时间来更新倒计时的显示。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值