5秒15秒后发送警报......使用计时器

时间:2016-04-18 18:15:37

标签: jquery timer elapsed

我已经制作了一个计时器,但我需要每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');
}

1 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;