当前位置:首页 > 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小时后

添加天数显示

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

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
分享给朋友:

相关文章

css3结合js制作

css3结合js制作

CSS3 结合 JavaScript 制作动态效果 CSS3 和 JavaScript 结合可以实现丰富的动态效果,包括动画、交互和响应式设计。以下是几种常见的实现方式: CSS3 动画与 Java…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

js 实现继承

js 实现继承

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

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…