js实现秒表
实现秒表的基本思路
使用JavaScript实现秒表需要记录开始时间、暂停时间和总运行时间。通过Date对象或performance.now()获取高精度时间戳,结合setInterval更新显示。
核心代码结构
class Stopwatch {
constructor(displayElement) {
this.display = displayElement;
this.running = false;
this.startTime = 0;
this.pausedTime = 0;
this.totalElapsed = 0;
}
start() {
if (!this.running) {
this.startTime = Date.now() - this.totalElapsed;
this.running = true;
this.updateDisplay();
}
}
pause() {
if (this.running) {
this.totalElapsed = Date.now() - this.startTime;
this.running = false;
}
}
reset() {
this.running = false;
this.totalElapsed = 0;
this.updateDisplay();
}
updateDisplay() {
if (this.running) {
const elapsed = Date.now() - this.startTime;
this.display.textContent = this.formatTime(elapsed);
requestAnimationFrame(() => this.updateDisplay());
} else {
this.display.textContent = this.formatTime(this.totalElapsed);
}
}
formatTime(ms) {
const date = new Date(ms);
return date.toISOString().substr(11, 8);
}
}
HTML部分
<div id="display">00:00:00</div>
<button id="startBtn">Start</button>
<button id="pauseBtn">Pause</button>
<button id="resetBtn">Reset</button>
初始化与事件绑定
const display = document.getElementById('display');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
const resetBtn = document.getElementById('resetBtn');
const stopwatch = new Stopwatch(display);
startBtn.addEventListener('click', () => stopwatch.start());
pauseBtn.addEventListener('click', () => stopwatch.pause());
resetBtn.addEventListener('click', () => stopwatch.reset());
性能优化方案
使用requestAnimationFrame替代setInterval实现更流畅的动画效果。对于高精度需求,可用performance.now()替代Date.now(),其精度达到微秒级。
// 修改start方法中的时间获取方式
this.startTime = performance.now() - this.totalElapsed;
// 修改updateDisplay中的计算方式
const elapsed = performance.now() - this.startTime;
扩展功能
添加分段计时功能:

class Stopwatch {
// ...原有代码...
addLap() {
if (this.running) {
const lapTime = Date.now() - this.startTime;
console.log(`Lap: ${this.formatTime(lapTime)}`);
}
}
}
// 添加按钮事件
document.getElementById('lapBtn').addEventListener('click', () => stopwatch.addLap());






