StopWatch作成

目標

htmlとcssとvanillaJS(素のJavascript)を使って簡易的なストップウォッチを作成しよう

解答例
html
<div class="container">
  <h1>ストップウォッチ</h1>
  <div class="stop-watch">
    <p class="display">0.00</p>
    <div class="button-container">
      <button class="btn btn-outline-primary" id="start">スタート</button>
      <button class="btn btn-outline-primary" id="stop">ストップ</button>
      <button class="btn btn-outline-primary" id="reset">リセット</button>
    </div>
  </div>
</div>
css
.container {
  text-align: center;
  h1 {
    margin-top: 36px;
  }
  .display {
    font-size: 4rem;
  }
}
javascript
window.onload = function () {
  const startButton = document.getElementById("start");
  const stopButton = document.getElementById("stop");
  const resetButton = document.getElementById("reset");
  const display = document.getElementById("display");
  let startTime, timer;
  let stopTime = 0;
  startButton.onclick = start;
  resetButton.onclick = reset;
  function start() {
    startButton.onclick = null;
    stopButton.onclick = stop;
    startTime = new Date();
    timer = setInterval(function () {
      const now = new Date();
      display.innerHTML = (
        (now - startTime + Number(stopTime) * 1000) /
        1000
      ).toFixed(2);
    }, 10);
  }
  function reset() {
    clearInterval(timer);
    startButton.onclick = start;
    stopButton.onclick = stop;
    display.innerHTML = "0.00";
    stopTime = 0;
  }
  function stop() {
    clearInterval(timer);
    stopTime = display.innerHTML;
    startButton.onclick = start;
    stopButton.onclick = null;
  }
};
動作例