带有单圈时间的秒表 JavaScript(如 iPhone 秒表)
Posted
技术标签:
【中文标题】带有单圈时间的秒表 JavaScript(如 iPhone 秒表)【英文标题】:Stopwatch JavaScript with lap times (like iPhone Stopwatch) 【发布时间】:2021-11-06 10:10:57 【问题描述】:我用 javascript 编写了一个简单的秒表。但是,我无法实现返回单圈时间的函数。
我的目标是编写一个秒表,就像 iPhone 中的秒表一样工作。我需要测量累计时间和单圈时间(不仅仅是分段时间)。
也许,有人已经编写过这样的秒表吗?
非常感谢,
//TIMER
function timeToString(time)
document.getElementById("time").value = time;
return time;
let startTime;
let start_date;
let elapsedTime = 0;
let timerInterval;
//FUNCTION TO CHANGE INNER html
function print(txt)
document.getElementById("display").innerHTML = txt;
//CREATE START PAUSE FUNCTION
function start()
startTime = performance.now() - elapsedTime;
start_date = performance.now()
timerInterval = setInterval(function printTime()
elapsedTime = performance.now() - startTime;
print(timeToString(elapsedTime));
, 10);
showButton("PAUSE");
function pause()
clearInterval(timerInterval);
showButton("PLAY");
//FUNCTION TO DISPLAY BUTTONS
function showButton(buttonKey)
const buttonToShow = buttonKey === "PLAY" ? openButton : closeButton;
const buttonToHide = buttonKey === "PLAY" ? closeButton : openButton;
buttonToShow.style.display = "block";
buttonToHide.style.display = "none";
//EVENT LISTENER
let openButton = document.getElementById("openButton");
let closeButton = document.getElementById("closeButton");
openButton.addEventListener("click", start);
closeButton.addEventListener("click", pause);
<button type="button" id="search_button" data-id="search_decision">
<span id="openButton">Start</span>
<span id="closeButton">Stop</span>
</button>
<p id="display">0</p>
<input type="hidden" name="time" id="time" value="0" />
【问题讨论】:
【参考方案1】:我不知道你是否想要观察者,请添加更多详细信息
class Stopwatch
constructor()
this.time = 0
this.laps = []
this.observers = []
stop()
clearInterval(this.timerInterval)
start()
this.timerInterval = setInterval(() => this.time++,1000)
lap()
this.laps.push(this.time)
getTimeForLab(index)
return this.laps[index] - (this.laps[index - 1] || 0)
const stopwatch = new Stopwatch()
stopwatch.start()
stopwatch.stop()
【讨论】:
以上是关于带有单圈时间的秒表 JavaScript(如 iPhone 秒表)的主要内容,如果未能解决你的问题,请参考以下文章
Javascript:如何从给定的 HH:MM:SS 开始秒表?