【问题标题】:Stopwatch JavaScript with lap times (like iPhone Stopwatch)带有单圈时间的秒表 JavaScript(如 iPhone 秒表)
【发布时间】: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" />

【问题讨论】:

    标签: javascript stopwatch


    【解决方案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()
    
    
    

    【讨论】:

      猜你喜欢
      • 2015-10-20
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      相关资源
      最近更新 更多