当前位置:首页 > 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.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

jquery js

jquery js

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

js实现游标

js实现游标

使用JavaScript实现游标 在JavaScript中,可以通过操作DOM元素的cursor样式属性来实现自定义游标效果。以下是几种常见的实现方法: 修改默认鼠标指针样式 通过CSS的curso…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…

js实现上传图片

js实现上传图片

使用HTML5的File API实现图片上传 HTML5的File API允许通过JavaScript访问用户选择的文件。需要创建一个文件输入元素,并监听其change事件。 <input t…

js实现删除

js实现删除

使用 splice 方法删除数组元素 splice 方法可以删除数组中的元素,并返回被删除的元素。它接受两个参数:起始索引和要删除的元素数量。 const array = [1, 2, 3, 4…