JavaScript:倒计时功能 | 豆包MarsCode AI刷题

292 阅读2分钟

倒计时功能的设计与实现

设计部分

理想功能状态: 我们想要设计一个倒计时的计时器工具,当我们点击页面上的按钮时就开始计时,在计时结束后在页面上打印出“倒计时结束”。

  • 定时器 setinterval():设置时间间隔,进行更新。

  • 时间戳(Timestamp):

时间戳是啥呢->是表示特定时间点的数值,通常以自1970年1月1日00:00:00 以来的秒数或毫秒数来表示。这个时间点被称为Unix纪元(Unix epoch)。时间戳广泛用于计算机系统中,用于记录事件发生的精确时间。

image.png

  • 时间戳通常是一个整数或者浮点数,分为秒级和毫秒级
  • 常见编程语言都有相应的函数和方法来使用时间戳

实现部分

时间戳的获取:

  • new Date() 创建一个 Date 对象,表示当前日期和时间。
  • new Date('2024-12-31T23:59:59') 创建一个 Date 对象,表示指定的日期和时间。
  • .getTime() 方法返回一个表示日期和时间的毫秒数,从1970年1月1日00:00:00 UTC开始计算。 时间差计算:计算两个时间戳之间的差值,得到剩余时间的毫秒数。

示例如下

const targetDate = new Date('2023-12-31T23:59:59').getTime();
const now = new Date().getTime();

时间单位转换:

  • 使用 Math.floor 方法将剩余时间的毫秒数转换为天、小时、分钟和秒。
  • % 运算符用于取模,计算剩余时间的各个部分。

示例如下

const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

---其中math是一个内置的全局对象,提供许多的使用方法,上述math.floor方法就是math对象的一个静态方法,可以直接调用------

更新页面:

  • 使用 document.getElementById 获取页面中的元素。
  • 使用模板字符串(`${}`)将计算结果插入到页面中

示例如下

document.getElementById('countdown').innerHTML = `${days}${hours}小时 ${minutes}分钟 ${seconds}秒`;

定时器使用:

  • setInterval 方法用于每隔一定时间(以毫秒为单位)执行一次指定的函数。
  • clearInterval 方法用于停止定时器。 倒计时结束处理:
  • 当时间差小于0时,表示倒计时已经结束,停止定时器并更新界面显示“倒计时结束”。

示例如下

if (timeDifference < 0) { clearInterval(interval); document.getElementById('countdown').innerHTML = '倒计时结束'; }

完整代码


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>倒计时计时器</title>
    <style>
        #countdown {
            font-size: 2em;
            text-align: center;
            margin-top: 50px;
        }
    </style>
</head>
<body>
    <div id="countdown"></div>

    <script>
        // 目标时间的时间戳(例如2024年12月31日23:59:59)
        const targetDate = new Date('2024-12-31T23:59:59').getTime();

        function updateCountdown() {
            // 获取当前时间的时间戳
            const now = new Date().getTime();

            // 计算时间差
            const timeDifference = targetDate - now;

            // 转换为可读格式
            const days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
            const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeDifference % (1000 * 60)) / 1000);

            // 更新界面
            document.getElementById('countdown').innerHTML = `${days}${hours}小时 ${minutes}分钟 ${seconds}秒`;

            // 如果时间差小于0,表示倒计时结束
            if (timeDifference < 0) {
                clearInterval(interval);
                document.getElementById('countdown').innerHTML = '倒计时结束';
            }
        }

        // 每秒更新一次倒计时
        const interval = setInterval(updateCountdown, 1000);

        // 立即更新一次倒计时
        updateCountdown();
    </script>
</body>
</html>


预览效果如下

image.png

到这我们就使用JavaScript做出了一个超级简易版倒计时计时器,要实现更复杂的功能,我还得继续学习才行~ 特别感谢Marscode老师~