窗口加载时启动计时器

时间:2018-10-21 04:40:05

标签: javascript html

我下面有一些代码,它是一个正向计时器,当我按 start 时,它开始以hh / mm / ss进行计数,而当我按显示所用时间时,显示标签内以hh / mm / ss表示的时间,并在单击按钮时将计数器重置为零,然后从零开始计数。

我的问题是,计时器最初仅在按开始按钮时才开始计时。

我想使计时器在窗口加载时自动启动并删除启动按钮。

如何实现?

window.onload = () => {
  let hour = 0;
  let minute = 0;
  let seconds = 0;
  let totalSeconds = 0;

  let intervalId = null;

  function startTimer() {
    ++totalSeconds;
    hour = Math.floor(totalSeconds / 3600);
    minute = Math.floor((totalSeconds - hour * 3600) / 60);
    seconds = totalSeconds - (hour * 3600 + minute * 60);

    document.getElementById("hour").innerHTML = hour;
    document.getElementById("minute").innerHTML = minute;
    document.getElementById("seconds").innerHTML = seconds;
  }

  document.getElementById('start-btn').addEventListener('click', () => {
    intervalId = setInterval(startTimer, 1000);
  })

  document.getElementById('Displplaytimetaken').addEventListener('click', () => {
    document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
    reset();
  });

  function reset() {
    totalSeconds = 0;
    document.getElementById("hour").innerHTML = '0';
    document.getElementById("minute").innerHTML = '0';
    document.getElementById("seconds").innerHTML = '0';
  }

}
<h1 style="font-size:24px;">Time Taken:
  <h1 id="timetaken"></h1>

  <button id="start-btn">Start</button>
  <button id="Displplaytimetaken">Display time taken</button>

2 个答案:

答案 0 :(得分:5)

window.onload = () => {
  let hour = 0;
  let minute = 0;
  let seconds = 0;
  let totalSeconds = 0;

  let intervalId = null;

intervalId = setInterval(startTimer, 1000);
  function startTimer() {
    ++totalSeconds;
    hour = Math.floor(totalSeconds / 3600);
    minute = Math.floor((totalSeconds - hour * 3600) / 60);
    seconds = totalSeconds - (hour * 3600 + minute * 60);

    document.getElementById("hour").innerHTML = hour;
    document.getElementById("minute").innerHTML = minute;
    document.getElementById("seconds").innerHTML = seconds;
  }

  

  document.getElementById('Displplaytimetaken').addEventListener('click', () => {
    document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
    reset();
  });

  function reset() {
    totalSeconds = 0;
    document.getElementById("hour").innerHTML = '0';
    document.getElementById("minute").innerHTML = '0';
    document.getElementById("seconds").innerHTML = '0';
  }

}
<h1 style="font-size:24px;">Time Taken:
  <h1 id="timetaken">

  </h1>

  <h2>    <span id="hour"></span>
    <span id="minute"></span>
    <span id="seconds"></span>
  </h2>

  <button id="Displplaytimetaken">Display time taken</button>

运行它,希望您的问题得到解决。

答案 1 :(得分:1)

尝试

<body onload="startTimer()">

在您的HTML中。

有帮助吗?