js实现时钟计时
使用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部分需包含一个显示元素的容器:

<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按钮:

<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);






