[JavaScript] 计时器

这是MDN教程上的一道练习题,
我的code:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>Simple setInterval clock</title>
    <style>
      p {
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <button class="start" id='start'>Start</button>
    <br><br><br>
    <button class="stop" id='stop'>Pause/Stop</button>
    <br><br><br>
    <button class="reset" id='reset'>Reset</button>
    <br><br><br>
    <p class="stopwatch"></p>

    <script>
      let watch;
      let bStartedOnce = false;
      let StartDate;
      let StopDate;
      let totalSeconds;
      let tempSeconds;

      function reset() {
        document.querySelector('.stopwatch').textContent = "00h : 00m : 00s";
        document.getElementById("start").disabled = false;
        bStartedOnce = false;
        document.getElementById("stop").disabled = true;
        document.getElementById("reset").disabled = true;
      }

      reset();

      let myStart = document.querySelector('.start');
      let myStop = document.querySelector('.stop');
      let myReset = document.querySelector('.reset');

      function showStopWatch(start) {
        let date = Date.now();
          totalSeconds = Math.floor((date-start)/1000);
        console.log(bStartedOnce);
        if (bStartedOnce)
          totalSeconds += tempSeconds;
        let hours = Math.floor(totalSeconds/3600);
        let minutes = Math.floor((totalSeconds-hours*3600)/60);
        let seconds = totalSeconds - minutes*60 - hours*3600;
        
        if (hours < 10)
          hours = "0" + hours;
        if (minutes < 10)
          minutes = "0" + minutes;
        if (seconds < 10)
          seconds = "0" + seconds;  

        document.querySelector('.stopwatch').textContent 
          = hours + "h : " + minutes + "m : " + seconds + "s";
      }

      function startStopWatch() {
        startDate = Date.now();
        watch = setInterval(showStopWatch, 1000, startDate);
        document.getElementById("start").disabled = true;
        document.getElementById("reset").disabled = true;
        document.getElementById("stop").disabled = false;
      }
 
      function stopStopWatch() {
        clearInterval(watch);
        document.getElementById("start").disabled = false;
        document.getElementById("reset").disabled = false;
        tempSeconds = totalSeconds;
        bStartedOnce = true;
        document.getElementById("stop").disabled = true;
      }

      myStart.addEventListener('click', startStopWatch);
      myStop.addEventListener('click', stopStopWatch);
      myReset.addEventListener('click', reset);

    </script>
  </body>
</html>

运行示意图:
在这里插入图片描述
下面是MDN答案:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>setInterval stopwatch</title>
    <style>
      p {
        font-family: sans-serif;
      }
    </style>
  </head>
  <body>
    <p class="clock"></p>
    <p><button class="start">Start</button><button class="stop">Stop</button><button class="reset">Reset</button></p>
    <script>
      // Define a counter variable for the number of seconds and set it to zero.
      let secondCount = 0;
      // Define a global to store the interval when it is active.
      let stopWatch;
      // Store a reference to the display paragraph in a variable
      const displayPara = document.querySelector('.clock');

      // Function to calculate the current hours, minutes, and seconds, and display the count
      function displayCount() {
        // Calculate current hours, minutes, and seconds
        let hours = Math.floor(secondCount/3600);
        let minutes = Math.floor((secondCount % 3600)/60);
        let seconds = Math.floor(secondCount % 60)

        // Display a leading zero if the values are less than ten
        let displayHours = (hours < 10) ? '0' + hours : hours;
        let displayMinutes = (minutes < 10) ? '0' + minutes : minutes;
        let displaySeconds = (seconds < 10) ? '0' + seconds : seconds;

        // Write the current stopwatch display time into the display paragraph
        displayPara.textContent = displayHours + ':' + displayMinutes + ':' + displaySeconds;

        // Increment the second counter by one
        secondCount++;
      }

      // Store references to the buttons in constants
      const startBtn = document.querySelector('.start');
      const stopBtn = document.querySelector('.stop');
      const resetBtn = document.querySelector('.reset');

      // When the start button is pressed, start running displayCount() once per second using displayInterval()
      startBtn.addEventListener('click', () => {
        stopWatch = setInterval(displayCount, 1000);
        startBtn.disabled = true;
      });

      // When the stop button is pressed, clear the interval to stop the count.
      stopBtn.addEventListener('click', () => {
        clearInterval(stopWatch);
        startBtn.disabled = false;
      });

      // When the reset button is pressed, set the counter back to zero, then immediately update the display
      resetBtn.addEventListener('click', () => {
        clearInterval(stopWatch);
        startBtn.disabled = false;
        secondCount = 0;
        displayCount();
      });

      // Run displayCount() once as soon as the page loads so the clock is displayed
      displayCount();
    </script>
  </body>
</html>

对应的UI如下:

在这里插入图片描述


Cooperative asynchronous JavaScript: Timeouts and intervals

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值