js 实现秒表
实现秒表功能
使用JavaScript实现秒表功能需要记录开始时间、暂停时间以及计算经过的时间。以下是一个完整的实现方案:

HTML结构
<div id="stopwatch">
<div id="display">00:00:00</div>
<button id="startBtn">Start</button>
<button id="pauseBtn" disabled>Pause</button>
<button id="resetBtn" disabled>Reset</button>
</div>
CSS样式
#stopwatch {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px auto;
width: 300px;
}
#display {
font-size: 48px;
margin-bottom: 20px;
}
button {
padding: 10px 20px;
margin: 0 5px;
font-size: 16px;
cursor: pointer;
}
JavaScript实现
class Stopwatch {
constructor(display, startBtn, pauseBtn, resetBtn) {
this.display = display;
this.startBtn = startBtn;
this.pauseBtn = pauseBtn;
this.resetBtn = resetBtn;
this.running = false;
this.startTime = 0;
this.elapsedTime = 0;
this.timer = null;
this.startBtn.addEventListener('click', () => this.start());
this.pauseBtn.addEventListener('click', () => this.pause());
this.resetBtn.addEventListener('click', () => this.reset());
}
start() {
if (!this.running) {
this.startTime = Date.now() - this.elapsedTime;
this.timer = setInterval(() => this.update(), 10);
this.running = true;
this.startBtn.disabled = true;
this.pauseBtn.disabled = false;
this.resetBtn.disabled = false;
}
}
pause() {
if (this.running) {
clearInterval(this.timer);
this.elapsedTime = Date.now() - this.startTime;
this.running = false;
this.startBtn.disabled = false;
this.pauseBtn.disabled = true;
}
}
reset() {
clearInterval(this.timer);
this.running = false;
this.elapsedTime = 0;
this.display.textContent = '00:00:00';
this.startBtn.disabled = false;
this.pauseBtn.disabled = true;
this.resetBtn.disabled = true;
}
update() {
const elapsed = Date.now() - this.startTime;
const hours = Math.floor(elapsed / 3600000);
const minutes = Math.floor((elapsed % 3600000) / 60000);
const seconds = Math.floor((elapsed % 60000) / 1000);
const milliseconds = Math.floor((elapsed % 1000) / 10);
this.display.textContent =
`${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}.${milliseconds.toString().padStart(2, '0')}`;
}
}
// 初始化秒表
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, pauseBtn, resetBtn);
功能说明
- 秒表显示格式为HH:MM:SS.ss(小时:分钟:秒.毫秒)
- 开始按钮启动计时器
- 暂停按钮暂停计时但不重置
- 重置按钮将秒表归零并停止计时
实现要点
- 使用Date.now()获取当前时间戳
- 使用setInterval每10毫秒更新一次显示
- 通过计算时间差来获取经过的时间
- 使用padStart方法格式化数字显示
- 按钮状态根据秒表状态动态变化
这个实现提供了完整的秒表功能,包括开始、暂停和重置操作,并显示小时、分钟、秒和毫秒。






