1

我做了一个计时器,但我需要每 5 或 10 秒发生一次。我不想使用 setTimeout 或 setInterval 函数,但是当我使用这个计时器时,我不知道如何处理秒的值。应该写成 5000 还是别的什么?

function display(){
    var endTime = new Date();
    var timeDiff = endTime - startTime;
    timeDiff /= 1000;

    var seconds = Math.round(timeDiff % 60);
    timeDiff = Math.floor(timeDiff / 60);

//showing the seconds passed
    $("#time").text(seconds);
    setTimeout(display,1000);
}

//starts the timer
$("#start").click(function() {
     startTime = new Date();
     setTimeout(display,1000);
});

/confirms it is 5 seconds
if (timeDiff == 5){
    alert('now');
}
4

1 回答 1

0

您的代码似乎没问题。如果它适用于计时器,那么您唯一需要做的就是通过以下方式在显示函数中移动 timeDiff 的条件检查:

<html>

<head>
  <script src="https://code.jquery.com/jquery-2.2.3.js" integrity="sha256-laXWtGydpwqJ8JA+X9x2miwmaiKhn8tVmOVEigRNtP4=" crossorigin="anonymous"></script>
  <script>
    $(document).ready(function(e) {


      var prevSec = 0,
        totalTime = 0;

      function display() {
        var endTime = new Date();
        var timeDiff = endTime - startTime;
        timeDiff /= 1000;

        var seconds = Math.round(timeDiff % 60);
        timeDiff = Math.floor(timeDiff / 60);

        //showing the seconds passed
        $("#time").text(seconds);
        //confirm it is 5 seconds
        if (seconds - prevSec == 5) {
          prevSec = seconds;
          totalTime = totalTime + 5;
          $("#text2").text("Another round of 5 seconds is over. Total time : " + totalTime + " seconds");
          // Do whatever you want

        }

        setTimeout(display, 1000);
      }

      //starts the timer
      $("#start").click(function() {
        startTime = new Date();
        setTimeout(display, 1000);
      });

    });
  </script>
</head>

<body>
  Time:
  <p id="time"></p>
  <button id="start">start</button>
  <br>
  <br>
  <br>Display Text :
  <p id="text2"></p>
</body>

</html>

于 2016-04-18T19:00:52.363 回答