为什么我的StopWatch无法正常工作

时间:2018-03-08 12:30:18

标签: javascript html

我必须创建一个带有开始按钮,停止按钮和暂停按钮的秒表。到目前为止,我已经达到启动和停止按钮但是没有工作。问题是什么我甚至要继续创建一个暂停按钮,如何做到这一点。请帮忙。

var seconds = 0,
  minutes = 0,
  hours = 0,
  timer;
var toStop = false;
var h1 = document.getElementsByTagName('h1')[0];

function start() {
  while (!toStop) {
    seconds++;
    if (seconds >= 60) {
      seconds = 0;
      minutes++;
      if (minutes >= 60) {
        minutes = 0;
        hours++;

        if (hours >= 12) {
          hours = 0;
          toStop = true;
          stop();
        }
      }
    }


    document.getElementById("h").value = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" +
      (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
      (seconds > 9 ? seconds : "0" + seconds);

    myTimer();
  }
}

function stop() {
  clearTimeout(myTimer());
  console.log(timer);
}

function myTimer() {
  timer = setInterval(start, 1000);
  console.log(timer);
}

function clear() {
  document.getElementById("h").value = "00:00:00";
  seconds = 0;
  minutes = 0;
  hours = 0;
}
<h1 id="h"><time>00:00:00</time></h1>

<button onclick="myTimer()">Start</button>
<button onclick="stop()">Stop</button>
<button onclick="clear()">Clear</button>

3 个答案:

答案 0 :(得分:0)

while (!toStop) {

摆脱它。 start() func应该只计算并打印经过的时间。另外,请勿在{{1​​}}中致电myTimer();。您已拨打start(),每秒拨打setInterval()

您应该在start()中创建一个Date对象,而不是按照您的方式计算经过的时间。然后在myTimer()创建另一个。要计算经过的时间,请从另一个中减去一个。

由于您致电start(),您应致电setInterval()停止。

clearInterval()
var startTime = null;
var timer = null;
var totalTime = 0;

function getElapsedTime()
{
    var now = new Date();
    return (now - startTime) / 1000;
}

function start() {
    // Calculate elapsed time since start btn was hit
    var elapsedTime = getElapsedTime();

    // Add prev times (from pause)
    elapsedTime += totalTime;
  
    // elapsedTime is in seconds. Calc, h/m/s
    var hours = Math.floor(elapsedTime / (60 * 60));
    elapsedTime %= (60 * 60);
    var minutes = Math.floor(elapsedTime / 60);
    elapsedTime %= 60;
    var seconds = Math.floor(elapsedTime);

    if (hours > 12) {
        stop();
    }
  
    // Build string
    var timeStr = (hours < 10 ? "0" : "") + hours + ":" + 
        (minutes < 10 ? "0" : "") + minutes + ":" +
        (seconds < 10 ? "0" : "") + seconds;
  
    // Update timer
    document.getElementById("h").textContent = timeStr;
    document.getElementById("h").value = timeStr;
}

var amPaused = false;
function pause()
{
    if (amPaused) {
        amPaused = false;
        startTime = new Date();
        timer = setInterval(start, 1000);
    }
    else {
        amPaused = true;
        totalTime += getElapsedTime();
        if (timer) {
            clearInterval(timer);
            timer = null;
        }
    }
}

function stop() {
    if (timer) {
       clearInterval(timer);
       timer = null;
    }
    amPaused = false;
    document.getElementById("start").disabled = false;
    document.getElementById("stop").disabled = true;
    document.getElementById("pause").disabled = true;
}

function myTimer() {
    stop();
    totalTime = 0;
    // Store the start time
    startTime = new Date();
    // Start the timer
    timer = setInterval(start, 1000);
    document.getElementById("start").disabled = true;
    document.getElementById("stop").disabled = false;
    document.getElementById("pause").disabled = false;
}

答案 1 :(得分:0)

&#13;
&#13;
<html>

<head>
    <title>
        Stop-Watch
    </title>
</head>

<body>
    <script>
        var myCounter;
        var seconds = 0, minutes = 0, hours = 0, timer;
        var toStop = false;
        var h1 = document.getElementsByTagName('h1')[0];

        function start() {
            if (!toStop) {
                seconds++;
                if (seconds >= 60) {
                    seconds = 0;
                    minutes++;
                    if (minutes >= 60) {
                        minutes = 0;
                        hours++;

                        if (hours >= 12) {
                            hours = 0;
                            toStop = true;
                            stop();
                        }
                    }
                }


                var time = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" +
                    (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" +
                    (seconds > 9 ? seconds : "0" + seconds);
                document.getElementById("h").innerHTML = time;

                // myTimer();
            }
        }
        function stop() {
            toStop = true;
            clearInterval(myCounter);
        }

        function myTimer() {
            if (!toStop) {
                document.getElementById("h").innerHTML = "00:00:00";
                seconds = 0; minutes = 0; hours = 0;
            }
            clearInterval(myCounter);
            toStop = false;
            myCounter = setInterval(start, 1000);

        }
        function clearTime() {
            toStop = true;
            seconds = 0; minutes = 0; hours = 0;
            clearInterval(myCounter);
            document.getElementById("h").innerHTML = "00:00:00";
        }
    </script>
    <h1>
        <time id="h">00:00:00</time>
    </h1>

    <button onclick="myTimer()">Start</button>
    <button onclick="stop()">Stop</button>
    <button onclick="clearTime()">Clear</button>
</body>

</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

不要使用while或阻止io事件的任何循环,因此浏览器无法更新html。

如果您想使用循环,那么您可以尝试async / await:

async start() {
  while (!stop) {
    await sleep(1000)
    // some code to get elapsedTime
    render()
  }
}
function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(() => resolve(), ms)
  })
}

但我喜欢避免使用循环来完成这项任务。

我相信它可能更少编码和更干净✨。

&#13;
&#13;
const timer = {
  start() {
    this.time = new Date()
    clearInterval(this.interval)
    this.interval = setInterval(() => { this.tick() }, 1000)
  },
  stop() {
    clearInterval(this.interval)
  },
  reset() {
    this.time = new Date()
    clearInterval(this.interval)
    this.render(0, 0, 0)
  },
  tick() {
    const now = new Date()
    const elapsedTime = new Date(now - this.time)
    const hours = elapsedTime.getUTCHours()
    const minutes = elapsedTime.getUTCMinutes()
    const seconds = elapsedTime.getUTCSeconds()
    if (hours >= 12) this.stop()
    this.render(hours, minutes, seconds)
  },
  render(hours, minutes, seconds) {
    const time = [hours, minutes, seconds].map(v => v.toString().padStart(2, `0`))
    const html = document.getElementById(`timer`)
    html.textContent = time.join(`:`)
  }
}
&#13;
<h1>
  <time id="timer">00:00:00</time>
</h1>
<button onclick="timer.start()">Start</button>
<button onclick="timer.stop()">Stop</button>
<button onclick="timer.reset()">Reset</button>
&#13;
&#13;
&#13;