当前位置:首页 > JavaScript

js实现时钟计时

2026-04-04 20:21:07JavaScript

使用JavaScript实现时钟计时

使用Date对象获取当前时间,并通过定时器更新显示。以下是基础实现代码:

function updateClock() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`;
}

setInterval(updateClock, 1000);
updateClock(); // 立即执行一次避免初始延迟

HTML部分需包含一个显示元素的容器:

js实现时钟计时

<div id="clock"></div>

添加计时器功能

实现开始、暂停、重置的计时器功能:

let timer;
let seconds = 0;

function startTimer() {
    if (!timer) {
        timer = setInterval(updateTimerDisplay, 1000);
    }
}

function pauseTimer() {
    clearInterval(timer);
    timer = null;
}

function resetTimer() {
    pauseTimer();
    seconds = 0;
    document.getElementById('timer').textContent = '00:00:00';
}

function updateTimerDisplay() {
    seconds++;
    const hrs = Math.floor(seconds / 3600).toString().padStart(2, '0');
    const mins = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
    const secs = (seconds % 60).toString().padStart(2, '0');
    document.getElementById('timer').textContent = `${hrs}:${mins}:${secs}`;
}

对应HTML按钮:

js实现时钟计时

<div id="timer">00:00:00</div>
<button onclick="startTimer()">Start</button>
<button onclick="pauseTimer()">Pause</button>
<button onclick="resetTimer()">Reset</button>

使用CSS美化样式

为时钟添加基础样式:

#clock, #timer {
    font-family: 'Arial', sans-serif;
    font-size: 2rem;
    color: #333;
    text-align: center;
    margin: 20px;
}

button {
    padding: 8px 16px;
    margin: 0 5px;
    font-size: 1rem;
}

性能优化建议

对于高精度计时需求,可使用requestAnimationFrame替代setInterval

let lastTimestamp = 0;
function animationFrameTimer(timestamp) {
    if (timestamp - lastTimestamp >= 1000) {
        updateClock(); // 或updateTimerDisplay
        lastTimestamp = timestamp;
    }
    requestAnimationFrame(animationFrameTimer);
}
requestAnimationFrame(animationFrameTimer);

标签: 时钟js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…