js实现计时器效果
实现基础计时器
使用 setInterval 创建基础计时器,每隔1秒更新显示时间:
let seconds = 0;
const timer = setInterval(() => {
seconds++;
console.log(`已运行: ${seconds}秒`);
}, 1000);
// 停止计时器
// clearInterval(timer);
格式化时间显示
将秒数转换为更易读的 HH:MM:SS 格式:
function formatTime(seconds) {
const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
const s = (seconds % 60).toString().padStart(2, '0');
return `${h}:${m}:${s}`;
}
带控制按钮的计时器
HTML 结构配合 JavaScript 实现完整控制:
<div id="timer">00:00:00</div>
<button id="start">开始</button>
<button id="pause">暂停</button>
<button id="reset">重置</button>
let timerId;
let seconds = 0;
const display = document.getElementById('timer');
document.getElementById('start').addEventListener('click', () => {
if (!timerId) {
timerId = setInterval(() => {
seconds++;
display.textContent = formatTime(seconds);
}, 1000);
}
});
document.getElementById('pause').addEventListener('click', () => {
clearInterval(timerId);
timerId = null;
});
document.getElementById('reset').addEventListener('click', () => {
clearInterval(timerId);
timerId = null;
seconds = 0;
display.textContent = '00:00:00';
});
使用 requestAnimationFrame 实现高精度计时
适合需要更高精度的场景:
let startTime;
let elapsedTime = 0;
let animationFrameId;
function updateTimer(timestamp) {
if (!startTime) startTime = timestamp;
elapsedTime = timestamp - startTime;
const seconds = Math.floor(elapsedTime / 1000);
document.getElementById('timer').textContent = formatTime(seconds);
animationFrameId = requestAnimationFrame(updateTimer);
}
// 启动
function start() {
animationFrameId = requestAnimationFrame(updateTimer);
}
// 停止
function stop() {
cancelAnimationFrame(animationFrameId);
}
带暂停功能的计时器
保存暂停时的状态以便恢复:
let startTime;
let pauseTime = 0;
let isRunning = false;
function startTimer() {
if (!isRunning) {
startTime = Date.now() - pauseTime;
isRunning = true;
updateDisplay();
}
}
function pauseTimer() {
if (isRunning) {
pauseTime = Date.now() - startTime;
isRunning = false;
clearTimeout(timerId);
}
}
function updateDisplay() {
if (isRunning) {
const elapsed = Date.now() - startTime;
document.getElementById('timer').textContent = formatTime(Math.floor(elapsed / 1000));
timerId = setTimeout(updateDisplay, 1000);
}
}





