js用时间差写一个倒计时怎么实现?

后台给了startTime和endTime的时间戳,通过他俩的差写一个倒计时,求解

阅读 3.6k
6 个回答

Countdown.vue:

<template>
  <span class="countdown">{{ hours }}:{{ minutes }}:{{ seconds }}</span>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";

// 设置开始时间和结束时间
const startTime = new Date("2023-08-01T19:00:00"); // 18:00 pm Aug 1th
const endTime = new Date("2023-08-03T19:00:00"); // 18:00 pm Aug 3th

// 计算倒计时的总秒数
const countdownTime = Math.floor((endTime - startTime) / 1000);

// 结束时间戳
const endTimestamp = ref(startTime.getTime() + countdownTime * 1000);

const hours = ref("00");
const minutes = ref("00");
const seconds = ref("00");

let intervalId;

const updateCountdown = () => {
  const remainingTime = endTimestamp.value - Date.now();

  if (remainingTime <= 0) {
    clearInterval(intervalId);
  } else {
    hours.value = String(Math.floor(remainingTime / 3600000)).padStart(2, "0");
    minutes.value = String(
      Math.floor((remainingTime % 3600000) / 60000)
    ).padStart(2, "0");
    seconds.value = String(Math.floor((remainingTime % 60000) / 1000)).padStart(
      2,
      "0"
    );
  }
};

onMounted(() => {
  updateCountdown();
  intervalId = setInterval(updateCountdown, 1000);
});

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

纯js:

let endTime = new Date("2023-12-31T23:59:59").getTime(); // 你的结束时间
let startTime = new Date().getTime(); // 你的开始时间

let countdown = setInterval(function() {
    let now = new Date().getTime();
    let distance = endTime - now;

    let hours = Math.floor(distance / (1000 * 60 * 60));
    let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((distance % (1000 * 60)) / 1000);

    console.log(hours + "h " + minutes + "m " + seconds + "s ");

    if (distance < 0) {
        clearInterval(countdown);
        console.log("Countdown Finished!");
    }
}, 1000);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
</body>
</html>
<script>
  // 设置开始时间和结束时间的时间戳(假设单位为毫秒)
const startTime = 1627950000000; // 开始时间的时间戳
const endTime = 1927971600000; // 结束时间的时间戳

// 计算倒计时的时间差(单位为毫秒)
const timeDiff = endTime - startTime;

// 定义更新倒计时的函数
function updateCountdown() {
  // 获取当前时间的时间戳
  const currentTime = Date.now();

  // 计算剩余时间的毫秒数
  const remainingTime = endTime - currentTime;

  // 如果剩余时间小于等于 0,说明倒计时已结束
  if (remainingTime <= 0) {
    console.log('倒计时已结束');
    clearInterval(timer); // 停止定时器
    return;
  }

  // 将剩余时间转换为小时、分钟和秒钟
  const hours = Math.floor(remainingTime / (1000 * 60 * 60));
  const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

  // 打印倒计时的小时、分钟和秒钟
  console.log(`倒计时:${hours} 小时 ${minutes} 分钟 ${seconds} 秒`);
}

// 每秒更新一次倒计时
const timer = setInterval(updateCountdown, 1000);
</script>

没说是vue几就当是vue2了,反正vue3也兼容vue2写法,主要是搞清楚时分秒怎么算
Vue playground

思路:剩余时间 = 结束时间 - 开始时间 - (当前时间 - 开始计时时间)

示例代码如下:

<span>剩余时间:{{ surplusFormat }}<span>
export default {
  name: "DemoCountdown",
  data() {
    return {
      // 剩余时间 (单位: ms)
      surplus: 0
    };
  },
  computed: {
    // 格式化剩余时间用于展示
    surplusFormat() {
      const total = Math.floor(this.surplus / 1000);

      const hours = Math.floor(total / 3600);
      const minutes = Math.floor((total % 3600) / 60);
      const seconds = total % 60;

      return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
    }
  },
  beforeDestroy() {
    this.destroyCountdownTimer();
  },
  methods: {
    /**
     * 启动倒计时定时器
     *
     * @param {number} start    开始时间戳 (13位)
     * @param {number} target   目标时间戳 (13位)
     */
    startCountdownTimer(start, target) {
      this.destroyCountdownTimer();

      this.surplus = target - start;

      // 开始计时时间
      const time = Date.now();

      this.timer = setInterval(() => {
        this.surplus = Math.max(0, target - start - (Date.now() - time));

        if (this.surplus <= 0) {
          this.destroyCountdownTimer();
        }
      }, 1000);
    },
    /**
     * 销毁倒计时定时器
     */
    destroyCountdownTimer() {
      if (this.timer != null) {
        clearInterval(this.timer);
        this.timer = null;
      }
    }
  }
};

vant组件有现成的 可以直接用哇

const calculateTimeLeft = (endTime, now) => {
    const distance = endTime - now;
    return Math.floor((distance % (1000 * 60)) / 1000);
}

const displayCountdown = timeLeft => {
    if (timeLeft <= 0) {
        console.log("Countdown finished");
    } else {
        console.log(timeLeft + "s");
    }
}

const countdown = (startTime, endTime) => {
    if (typeof startTime !== 'number' || typeof endTime !== 'number') {
        console.error("Invalid arguments: startTime and endTime should be numbers");
        return;
    }

    if (endTime <= startTime) {
        console.error("Invalid arguments: endTime should be greater than startTime");
        return;
    }
    
    const intervalId = setInterval(() => {
        const now = new Date().getTime();
        const timeLeft = calculateTimeLeft(endTime, now);
        displayCountdown(timeLeft);

        if (timeLeft <= 0) {
            clearInterval(intervalId);
        }
    }, 1000);
}

// 假设 startTime 和 endTime 是从后台获取的时间戳
const startTime = new Date().getTime();
const endTime = new Date().getTime() + 10000; // 10 秒后
countdown(startTime, endTime);

先定义一个calculateTimeLeft函数,这个函数接收两个参数endTimenow,分别表示倒计时的结束时间和当前时间。函数会返回距离结束还剩下的时间(以秒为单位)。

再定义一个displayCountdown函数,这个函数接收一个参数timeLeft,表示还剩下的时间。如果剩下的时间小于或等于0,那么就打印"Countdown finished";否则,就打印剩下的秒数。

然后定义了一个countdown函数,这个函数接收两个参数startTimeendTime,分别表示倒计时的开始时间和结束时间。函数首先检查两个参数是否都是数字,如果不是,就打印错误信息并返回。然后检查结束时间是否大于开始时间,如果不是,也打印错误信息并返回。

如果两个参数都没问题,那么就开始倒计时。函数会每秒获取一次当前时间,计算还剩下的时间,然后显示剩下的时间。如果剩下的时间小于或等于0,那么就取消这个定时器。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题