js 实现秒表

实现秒表的基本思路
使用JavaScript实现秒表需要利用Date对象或performance.now()来精确计时,通过setInterval或requestAnimationFrame更新显示时间。核心功能包括开始、暂停、重置和显示时间。
基本HTML结构
<div id="stopwatch">
<div id="display">00:00:00.000</div>
<button id="startBtn">开始</button>
<button id="pauseBtn">暂停</button>
<button id="resetBtn">重置</button>
</div>
JavaScript实现代码
class Stopwatch {
constructor(displayElement) {
this.display = displayElement;
this.isRunning = false;
this.startTime = 0;
this.elapsedTime = 0;
this.timer = null;
}
start() {
if (!this.isRunning) {
this.isRunning = true;
this.startTime = Date.now() - this.elapsedTime;
this.timer = setInterval(() => this.update(), 10);
}
}
pause() {
if (this.isRunning) {
this.isRunning = false;
clearInterval(this.timer);
}
}
reset() {
this.isRunning = false;
clearInterval(this.timer);
this.elapsedTime = 0;
this.update();
}
update() {
const currentTime = Date.now();
this.elapsedTime = currentTime - this.startTime;
this.display.textContent = this.formatTime(this.elapsedTime);
}
formatTime(milliseconds) {
const date = new Date(milliseconds);
const hours = date.getUTCHours().toString().padStart(2, '0');
const minutes = date.getUTCMinutes().toString().padStart(2, '0');
const seconds = date.getUTCSeconds().toString().padStart(2, '0');
const ms = date.getUTCMilliseconds().toString().padStart(3, '0');
return `${hours}:${minutes}:${seconds}.${ms}`;
}
}
// 初始化秒表
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());
高精度计时方案
对于需要更高精度的场景,可以使用performance.now()替代Date.now():
start() {
if (!this.isRunning) {
this.isRunning = true;
this.startTime = performance.now() - this.elapsedTime;
this.timer = requestAnimationFrame(() => this.update());
}
}
update() {
if (!this.isRunning) return;
const currentTime = performance.now();
this.elapsedTime = currentTime - this.startTime;
this.display.textContent = this.formatTime(this.elapsedTime);
this.timer = requestAnimationFrame(() => this.update());
}
pause() {
if (this.isRunning) {
this.isRunning = false;
cancelAnimationFrame(this.timer);
}
}
功能扩展建议
- 添加分段计时(Lap)功能
- 支持保存历史记录
- 添加主题切换或自定义样式
- 实现响应式设计适配移动设备
注意事项
setInterval在非活动标签页中可能会降低精度,requestAnimationFrame更适用于动画场景- 清除定时器时务必使用
clearInterval或cancelAnimationFrame - 时间格式化时注意时区问题(使用
getUTC方法避免时区影响)







