当前位置:首页 > JavaScript

js实现秒表

2026-02-01 06:00:51JavaScript

实现秒表功能

使用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()方法确保时间格式始终为两位数/三位数显示,保持界面整齐。

累计时间处理允许暂停后继续计时,而不是每次都从零开始。

js实现秒表

两种实现都支持显示小时、分钟、秒和毫秒,可根据需求调整格式函数。

标签: 秒表js
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js怎么实现异步

js怎么实现异步

异步实现方法 JavaScript中实现异步操作主要通过以下几种方式: Promise Promise是ES6引入的异步解决方案,用于处理异步操作的成功或失败状态。 const promise =…