js实现秒表盘

以下是用JavaScript实现秒表盘的代码示例,包含开始、暂停、重置功能,并显示毫秒级精度:
HTML结构
<div class="stopwatch">
<div class="display">00:00:00.000</div>
<button class="start">开始</button>
<button class="pause">暂停</button>
<button class="reset">重置</button>
</div>
CSS样式
.stopwatch {
text-align: center;
font-family: Arial, sans-serif;
}
.display {
font-size: 3em;
margin: 20px;
}
button {
padding: 10px 20px;
margin: 5px;
font-size: 1em;
cursor: pointer;
}
JavaScript实现
class Stopwatch {
constructor(display) {
this.display = display;
this.running = false;
this.startTime = null;
this.elapsedTime = 0;
this.timer = null;
}
start() {
if (!this.running) {
this.startTime = Date.now() - this.elapsedTime;
this.timer = setInterval(() => this.update(), 10);
this.running = true;
}
}
pause() {
if (this.running) {
clearInterval(this.timer);
this.elapsedTime = Date.now() - this.startTime;
this.running = false;
}
}
reset() {
clearInterval(this.timer);
this.running = false;
this.elapsedTime = 0;
this.display.textContent = '00:00:00.000';
}
update() {
const elapsed = Date.now() - this.startTime;
const milliseconds = Math.floor(elapsed % 1000);
const seconds = Math.floor((elapsed / 1000) % 60);
const minutes = Math.floor((elapsed / (1000 * 60)) % 60);
const hours = Math.floor(elapsed / (1000 * 60 * 60));
this.display.textContent =
`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(3, '0')}`;
}
}
// 初始化
const display = document.querySelector('.display');
const startBtn = document.querySelector('.start');
const pauseBtn = document.querySelector('.pause');
const resetBtn = document.querySelector('.reset');
const stopwatch = new Stopwatch(display);
startBtn.addEventListener('click', () => stopwatch.start());
pauseBtn.addEventListener('click', () => stopwatch.pause());
resetBtn.addEventListener('click', () => stopwatch.reset());
功能说明
- 开始:点击后开始计时,显示时:分:秒.毫秒格式
- 暂停:暂停当前计时,保留已计时数值
- 重置:将计时器归零,显示00:00:00.000
扩展建议
- 添加分段计时功能(记录多个时间点)
- 增加样式美化,如环形进度条显示
- 添加声音提示功能
- 支持键盘快捷键操作
该实现使用面向对象方式组织代码,便于维护和扩展。核心计时逻辑通过Date.now()获取时间戳,避免了setInterval的时间漂移问题。







