-4

我需要创建一个 javascript 计时器,它将倒计时到接下来的 5 分钟。例如,假设时间是 00:07:30,如果时间是 15:42:00,则时间会说 02:30,计时器会说 03:00 我真的想不出任何好的方法来解决这个问题。谢谢你。

4

3 回答 3

12

有很多方法可以做到这一点。我的想法是找出当前时间除以五分钟(300 秒)的提醒。

演示:http: //jsfiddle.net/txwsj/

setInterval(function () {
    var d = new Date(); //get current time
    var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet current mm:ss to seconds for easier caculation, we don't care hours.
    var fiveMin = 60 * 5; //five minutes is 300 seconds!
    var timeleft = fiveMin - seconds % fiveMin; // let's say now is 01:30, then current seconds is 60+30 = 90. And 90%300 = 90, finally 300-90 = 210. That's the time left!
    var result = parseInt(timeleft / 60) + ':' + timeleft % 60; //formart seconds back into mm:ss 
    document.getElementById('test').innerHTML = result;

}, 500) //calling it every 0.5 second to do a count down
于 2013-04-22T21:38:13.237 回答
0

相反,您可以尝试window.setInterval()像这样使用:

    window.setInterval(function(){
        var time = document.getElementById("secs").innerHTML;
        if (time > 0) {
            time -= 1;
        } else {
            alert ("times up!");
            //or whatever you want
        }
        document.getElementById("secs").innerHTML = time;
    }, 1000);
于 2013-05-04T23:59:42.103 回答
-1

如果你想在你的网页上做一个计时器,你可以尝试使用这样的东西:

<html>  
  <head>
    <script type="text/javascript">
      var now = new Date().getTime();
      var elapsed = new Date().getTime() - now;
      document.getElementById("timer").innerHtml = elapsed;
      if (elapsed > 300000 /*milliseconds in 5 minutes*/) {
        alert ("5 minutes up!");
        //take whatever action you want!
      }
    </script>
  </head>
  <body>
    <div id="timer"></div>
  </body>
</html>
于 2013-04-22T21:27:35.620 回答