2013-04-22 98 views
-4

我需要创建一个JavaScript计时器,将倒计时到下一个5分钟。 例如,假设时间是00:07:30,时间会说02:30 如果时间是15:42:00计时器会说03:00 我真的不能想到任何好方法杜这个。 谢谢。javascript倒计时到下一个真正的5分钟

+0

我没有尝试任何事情,我能想到的唯一的事情就是每5创建一个开关分钟在24小时内,这是redeculis。 – 2013-04-22 21:33:46

+0

看看这个,并按照链接和链接,你可能会问一个副本,http://stackoverflow.com/questions/16134997/how-to-pause-and-resume-a-javascript-timer – Xotic750 2013-04-22 21:35:44

+0

不,因为我需要使用真正的5分钟,而不是从现在开始的5分钟,而是在5分钟的时间内,05,10,15,20,25,30 ...... – 2013-04-22 21:38:22

回答

6

有很多方法可以做到这一点。我的想法是找出当前时间除以5分钟(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 
+0

完美!塔克你 – 2013-04-22 21:40:41

-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> 
+0

我需要一个真正的倒计时 – 2013-04-22 21:34:33

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);