当前位置:首页 > JavaScript

用js实现一个倒计时器

2026-01-31 12:22:33JavaScript

实现一个简单的倒计时器

创建一个基础的HTML文件结构,包含显示倒计时的元素

<!DOCTYPE html>
<html>
<head>
    <title>倒计时器</title>
    <style>
        #countdown {
            font-size: 48px;
            text-align: center;
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <div id="countdown">00:00:00</div>
    <script src="countdown.js"></script>
</body>
</html>

JavaScript倒计时逻辑

在countdown.js文件中实现倒计时功能

// 设置目标时间(这里设置为当前时间+1小时)
const targetTime = new Date().getTime() + 3600000;

// 更新倒计时显示
function updateCountdown() {
    const currentTime = new Date().getTime();
    const timeLeft = targetTime - currentTime;

    // 计算小时、分钟、秒
    const hours = Math.floor(timeLeft / (1000 * 60 * 60));
    const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

    // 格式化显示
    const formattedTime = 
        `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

    document.getElementById('countdown').textContent = formattedTime;

    // 倒计时结束处理
    if (timeLeft <= 0) {
        clearInterval(countdownInterval);
        document.getElementById('countdown').textContent = "时间到!";
    }
}

// 每秒更新一次
const countdownInterval = setInterval(updateCountdown, 1000);

// 立即执行一次避免初始延迟
updateCountdown();

可配置的倒计时器实现

创建一个更灵活的版本,允许设置自定义时间

function startCountdown(targetDate, displayElement) {
    // 验证目标日期是否有效
    if (!(targetDate instanceof Date) || isNaN(targetDate)) {
        displayElement.textContent = "无效日期";
        return null;
    }

    // 更新倒计时函数
    function update() {
        const now = new Date();
        const diff = targetDate - now;

        if (diff <= 0) {
            displayElement.textContent = "时间到!";
            return null;
        }

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

        displayElement.textContent = 
            `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

        return diff;
    }

    // 立即执行一次
    update();

    // 设置定时器
    return setInterval(update, 1000);
}

// 使用示例
const endTime = new Date();
endTime.setHours(endTime.getHours() + 1); // 1小时后
const timer = startCountdown(endTime, document.getElementById('countdown'));

添加暂停和继续功能

扩展倒计时器功能,增加交互控制

function createCountdownController(targetDate, displayElement) {
    let intervalId = null;
    let remainingTime = targetDate - new Date();

    function updateDisplay(time) {
        const hours = Math.floor(time / (1000 * 60 * 60));
        const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((time % (1000 * 60)) / 1000);

        displayElement.textContent = 
            `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    }

    function start() {
        if (intervalId) clearInterval(intervalId);

        function tick() {
            remainingTime -= 1000;

            if (remainingTime <= 0) {
                clearInterval(intervalId);
                displayElement.textContent = "时间到!";
                return;
            }

            updateDisplay(remainingTime);
        }

        updateDisplay(remainingTime);
        intervalId = setInterval(tick, 1000);
    }

    function pause() {
        if (intervalId) {
            clearInterval(intervalId);
            intervalId = null;
        }
    }

    function reset(newTargetDate) {
        pause();
        remainingTime = newTargetDate - new Date();
        updateDisplay(remainingTime);
    }

    return {
        start,
        pause,
        reset
    };
}

// 使用示例
const controller = createCountdownController(
    new Date(Date.now() + 3600000), // 1小时后
    document.getElementById('countdown')
);

controller.start(); // 开始倒计时
// controller.pause(); // 暂停倒计时
// controller.reset(new Date(Date.now() + 7200000)); // 重置为2小时后

添加天数显示

对于较长的倒计时,可以添加天数显示

用js实现一个倒计时器

function formatTimeWithDays(ms) {
    const days = Math.floor(ms / (1000 * 60 * 60 * 24));
    const hours = Math.floor((ms % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((ms % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((ms % (1000 * 60)) / 1000);

    return `${days}d ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}

// 在更新函数中使用
function update() {
    const now = new Date();
    const diff = targetDate - now;

    if (diff <= 0) {
        displayElement.textContent = "时间到!";
        return null;
    }

    displayElement.textContent = formatTimeWithDays(diff);
    return diff;
}

标签: 计时器js
分享给朋友:

相关文章

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js 实现链表

js 实现链表

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和指向下一个节点的指针。与数组不同,链表在内存中是非连续存储的,插入和删除操作效率较高。 链表的实现 在 JavaScrip…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…

js 实现全屏

js 实现全屏

使用 requestFullscreen 方法 通过调用元素的 requestFullscreen 方法可以实现全屏。该方法兼容现代浏览器,但不同浏览器可能需要前缀。 const element =…