js秒表实现
实现 JavaScript 秒表
基本 HTML 结构
创建一个简单的 HTML 结构,包含显示时间和控制按钮:
<div id="stopwatch">
<div id="display">00:00:00</div>
<button id="startBtn">开始</button>
<button id="stopBtn">停止</button>
<button id="resetBtn">重置</button>
</div>
CSS 样式(可选)
添加基本样式美化秒表:
#stopwatch {
text-align: center;
font-family: Arial, sans-serif;
}
#display {
font-size: 2em;
margin: 20px;
}
button {
padding: 10px 20px;
margin: 5px;
font-size: 1em;
}
JavaScript 核心逻辑
实现秒表功能的核心代码:
let startTime;
let elapsedTime = 0;
let timerInterval;
function formatTime(time) {
let hours = Math.floor(time / 3600000);
let minutes = Math.floor((time % 3600000) / 60000);
let seconds = Math.floor((time % 60000) / 1000);
let milliseconds = Math.floor(time % 1000);
return (
String(hours).padStart(2, "0") + ":" +
String(minutes).padStart(2, "0") + ":" +
String(seconds).padStart(2, "0") + "." +
String(milliseconds).padStart(3, "0").slice(0, 2)
);
}
function startTimer() {
startTime = Date.now() - elapsedTime;
timerInterval = setInterval(function() {
elapsedTime = Date.now() - startTime;
document.getElementById("display").textContent = formatTime(elapsedTime);
}, 10);
}
function stopTimer() {
clearInterval(timerInterval);
}
function resetTimer() {
clearInterval(timerInterval);
elapsedTime = 0;
document.getElementById("display").textContent = "00:00:00.00";
}
document.getElementById("startBtn").addEventListener("click", startTimer);
document.getElementById("stopBtn").addEventListener("click", stopTimer);
document.getElementById("resetBtn").addEventListener("click", resetTimer);
高级功能扩展
添加计次功能:
let lapTimes = [];
const lapList = document.createElement("ol");
document.getElementById("stopwatch").appendChild(lapList);
function recordLap() {
lapTimes.push(formatTime(elapsedTime));
const lapItem = document.createElement("li");
lapItem.textContent = lapTimes[lapTimes.length - 1];
lapList.appendChild(lapItem);
}
// 添加计次按钮到HTML
const lapBtn = document.createElement("button");
lapBtn.textContent = "计次";
lapBtn.id = "lapBtn";
document.getElementById("stopwatch").appendChild(lapBtn);
document.getElementById("lapBtn").addEventListener("click", recordLap);
性能优化建议
使用 requestAnimationFrame 替代 setInterval:
function startTimer() {
startTime = Date.now() - elapsedTime;
function updateTimer() {
elapsedTime = Date.now() - startTime;
document.getElementById("display").textContent = formatTime(elapsedTime);
timerInterval = requestAnimationFrame(updateTimer);
}
timerInterval = requestAnimationFrame(updateTimer);
}
function stopTimer() {
cancelAnimationFrame(timerInterval);
}
注意事项
- 确保按钮事件绑定在DOM加载完成后执行
- 考虑添加暂停功能而不仅仅是停止
- 移动端适配可能需要调整按钮大小和间距
- 长时间运行时注意内存管理







