js实现秒表

实现秒表功能
使用JavaScript实现秒表功能可以通过Date对象或performance.now()来精确计时。以下是两种常见的实现方式。

使用Date对象实现秒表
let startTime;
let elapsedTime = 0;
let timerInterval;
function startStopwatch() {
startTime = new Date().getTime() - elapsedTime;
timerInterval = setInterval(updateStopwatch, 10);
}
function stopStopwatch() {
clearInterval(timerInterval);
}
function resetStopwatch() {
clearInterval(timerInterval);
elapsedTime = 0;
document.getElementById("display").textContent = "00:00:00.000";
}
function updateStopwatch() {
const currentTime = new Date().getTime();
elapsedTime = currentTime - startTime;
const formattedTime = formatTime(elapsedTime);
document.getElementById("display").textContent = formattedTime;
}
function formatTime(time) {
const hours = Math.floor(time / (1000 * 60 * 60));
const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((time % (1000 * 60)) / 1000);
const milliseconds = Math.floor(time % 1000);
return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}.${pad(milliseconds, 3)}`;
}
function pad(num, size = 2) {
return num.toString().padStart(size, '0');
}
使用performance.now()实现秒表
performance.now()提供了更高精度的计时,适合需要更精确计时的场景。
let startTime;
let elapsedTime = 0;
let timerInterval;
function startStopwatch() {
startTime = performance.now() - elapsedTime;
timerInterval = requestAnimationFrame(updateStopwatch);
}
function stopStopwatch() {
cancelAnimationFrame(timerInterval);
}
function resetStopwatch() {
cancelAnimationFrame(timerInterval);
elapsedTime = 0;
document.getElementById("display").textContent = "00:00:00.000";
}
function updateStopwatch() {
const currentTime = performance.now();
elapsedTime = currentTime - startTime;
const formattedTime = formatTime(elapsedTime);
document.getElementById("display").textContent = formattedTime;
timerInterval = requestAnimationFrame(updateStopwatch);
}
function formatTime(time) {
const hours = Math.floor(time / (1000 * 60 * 60));
const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((time % (1000 * 60)) / 1000);
const milliseconds = Math.floor(time % 1000);
return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}.${pad(milliseconds, 3)}`;
}
function pad(num, size = 2) {
return num.toString().padStart(size, '0');
}
HTML部分
<div id="display">00:00:00.000</div>
<button onclick="startStopwatch()">Start</button>
<button onclick="stopStopwatch()">Stop</button>
<button onclick="resetStopwatch()">Reset</button>
CSS部分(可选)
#display {
font-family: monospace;
font-size: 2em;
margin: 20px;
}
button {
padding: 10px 20px;
margin: 5px;
font-size: 1em;
}
注意事项
performance.now()提供微秒级精度,但可能受浏览器限制。setInterval的精度可能受系统负载影响,requestAnimationFrame更适合平滑动画。- 使用
padStart确保时间格式始终为两位数,保持显示一致。






