js 实现秒表
实现秒表功能
使用JavaScript实现秒表功能可以通过Date对象或performance.now()来精确计时。以下是两种常见实现方式:
方法一:基于Date对象的秒表
class Stopwatch {
constructor() {
this.startTime = 0;
this.elapsedTime = 0;
this.isRunning = false;
}
start() {
if (!this.isRunning) {
this.startTime = Date.now() - this.elapsedTime;
this.isRunning = true;
this.timer = setInterval(() => this.updateDisplay(), 10);
}
}
pause() {
if (this.isRunning) {
clearInterval(this.timer);
this.elapsedTime = Date.now() - this.startTime;
this.isRunning = false;
}
}
reset() {
clearInterval(this.timer);
this.elapsedTime = 0;
this.isRunning = false;
document.getElementById('display').textContent = '00:00:00.000';
}
updateDisplay() {
const elapsed = Date.now() - this.startTime;
const formattedTime = this.formatTime(elapsed);
document.getElementById('display').textContent = formattedTime;
}
formatTime(milliseconds) {
const date = new Date(milliseconds);
return date.toISOString().substr(11, 12).replace('.', ':');
}
}
// 使用示例
const stopwatch = new Stopwatch();
方法二:基于performance.now()的高精度秒表

class HighResStopwatch {
constructor() {
this.startTime = 0;
this.pausedTime = 0;
this.isRunning = false;
}
start() {
if (!this.isRunning) {
this.startTime = performance.now() - this.pausedTime;
this.isRunning = true;
requestAnimationFrame(() => this.update());
}
}
pause() {
if (this.isRunning) {
this.pausedTime = performance.now() - this.startTime;
this.isRunning = false;
}
}
reset() {
this.pausedTime = 0;
this.isRunning = false;
document.getElementById('display').textContent = '00:00:00.000';
}
update() {
if (this.isRunning) {
const elapsed = performance.now() - this.startTime;
document.getElementById('display').textContent = this.formatTime(elapsed);
requestAnimationFrame(() => this.update());
}
}
formatTime(milliseconds) {
const date = new Date(milliseconds);
return date.toISOString().substr(11, 12).replace('.', ':');
}
}
HTML结构示例
<div id="stopwatch">
<div id="display">00:00:00.000</div>
<button onclick="stopwatch.start()">Start</button>
<button onclick="stopwatch.pause()">Pause</button>
<button onclick="stopwatch.reset()">Reset</button>
</div>
CSS样式建议
#stopwatch {
font-family: monospace;
font-size: 2em;
text-align: center;
}
#display {
margin: 20px;
}
button {
padding: 10px 20px;
margin: 5px;
font-size: 1rem;
}
注意事项
performance.now()提供更高精度的时间测量(微秒级)- 使用
requestAnimationFrame比setInterval更适合动画和频繁更新的显示 - 清除定时器或动画帧很重要,避免内存泄漏
- 时间格式化可以根据需求调整显示格式
两种实现方式都可以扩展添加更多功能,如分段时间记录、多计时器等。根据项目需求选择合适的方法,高精度计时推荐使用performance.now()方案。






