单击鼠标的时间跟踪 Javascript

Time Tracking on mouse click Javascript

我想制作一个在浏览器中运行的非常简单的时间跟踪器。这是我能想出的最简单的代码,但我在点击事件方面遇到了问题。问题是整个事情都有效,但它在页面加载时开始,我希望它在点击时开始。执行有问题吗?

这是我的代码:

let hours = 0;
let minutes = 0;
let seconds = 0;
function time() {
  setInterval(function () {
    if (seconds < 59) {
      seconds++;
      document.getElementById("timer").textContent =
        hours + ":" + minutes + ":" + seconds;
    } else if (minutes < 59) {
      seconds = 0;
      minutes++;
      document.getElementById("timer").textContent =
        hours + ":" + minutes + ":" + seconds;
    } else {
      hours++;
      document.getElementById("timer").textContent =
        hours + ":" + minutes + ":" + seconds;
    }
  }, 1000);
}

document.getElementById("button").addEventListener("click", time());
body {
  background-color: blanchedalmond;
}
div {
  margin-top: 200px;
  display: flex;
  align-items: center;
  flex-direction: column;
}
#timer {
  min-height: 80px;
  font-size: 4em;
}
h1 {
  display: block;
}
#button {
  margin-top: 50px;
  width: 180px;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="script.js"></script>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="a">
      <h1 id="header">You have been working for:</h1>
      <time id="timer">0:0:0</time>
      <button id="button" class="btn btn-primary">Track Time</button>
    </div>
  </body>
</html>

问题是您在添加事件侦听器时调用了 time 函数。为了 运行 仅在单击按钮时调用 time 函数,请不要立即调用 time 函数:

document.getElementById("button").addEventListener("click", time);

您必须使用这样的语法,因为您的点击功能在添加事件侦听器时已经触发。

document.getElementById("button").addEventListener("click", function(){
    time();
});