js实现秒表
实现秒表功能
使用JavaScript实现秒表功能可以通过Date对象或performance.now()来精确计时,结合setInterval控制更新频率。以下是两种常见实现方式:
基于Date对象的秒表
let startTime;
let timerInterval;
let isRunning = false;
function startStopwatch() {
if (isRunning) return;
startTime = new Date().getTime();
timerInterval = setInterval(updateDisplay, 10);
isRunning = true;
}
function stopStopwatch() {
clearInterval(timerInterval);
isRunning = false;
}
function resetStopwatch() {
stopStopwatch();
document.getElementById("display").textContent = "00:00:00.000";
}
function updateDisplay() {
const currentTime = new Date().getTime();
const elapsedTime = currentTime - startTime;
const formattedTime = formatTime(elapsedTime);
document.getElementById("display").textContent = formattedTime;
}
function formatTime(milliseconds) {
const date = new Date(milliseconds);
const hours = date.getUTCHours().toString().padStart(2, '0');
const minutes = date.getUTCMinutes().toString().padStart(2, '0');
const seconds = date.getUTCSeconds().toString().padStart(2, '0');
const ms = date.getUTCMilliseconds().toString().padStart(3, '0');
return `${hours}:${minutes}:${seconds}.${ms}`;
}
基于performance.now()的高精度秒表
let startTimestamp;
let accumulatedTime = 0;
let timerInterval;
let isRunning = false;
function startStopwatch() {
if (isRunning) return;
startTimestamp = performance.now();
timerInterval = setInterval(updateDisplay, 10);
isRunning = true;
}
function stopStopwatch() {
if (!isRunning) return;
accumulatedTime += performance.now() - startTimestamp;
clearInterval(timerInterval);
isRunning = false;
}
function resetStopwatch() {
stopStopwatch();
accumulatedTime = 0;
document.getElementById("display").textContent = "00:00:00.000";
}
function updateDisplay() {
const currentTime = isRunning
? accumulatedTime + (performance.now() - startTimestamp)
: accumulatedTime;
const formattedTime = formatTime(currentTime);
document.getElementById("display").textContent = formattedTime;
}
function formatTime(milliseconds) {
const totalSeconds = Math.floor(milliseconds / 1000);
const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0');
const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '0');
const seconds = (totalSeconds % 60).toString().padStart(2, '0');
const ms = Math.floor(milliseconds % 1000).toString().padStart(3, '0');
return `${hours}:${minutes}:${seconds}.${ms}`;
}
HTML结构示例
<div id="display">00:00:00.000</div>
<button onclick="startStopwatch()">Start</button>
<button onclick="stopStopwatch()">Stop</button>
<button onclick="resetStopwatch()">Reset</button>
关键点说明
performance.now()比Date.now()提供更高精度的时间测量(微秒级),且不受系统时间调整影响。

定时器间隔设置为10ms(实际精度受浏览器限制),可根据需要调整为更小值(如1ms)或更大值(如100ms)。

使用padStart()方法确保时间格式始终为两位数/三位数显示,保持界面整齐。
累计时间处理允许暂停后继续计时,而不是每次都从零开始。
两种实现都支持显示小时、分钟、秒和毫秒,可根据需求调整格式函数。






