Секундомер JavaScript с указанием времени прохождения круга (например, секундомер iPhone)

#javascript #stopwatch

Вопрос:

Я запрограммировал простой секундомер на 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()