我需要创建一个javascript计时器,计数到接下来的5分钟。 例如,假设时间是00:07:30,时间会说02:30 如果时间是15:42:00,计时器会说03:00 我真的想不出有什么好办法去做。 谢谢。
答案 0 :(得分:7)
有很多方法可以做到这一点。我的想法是找出当前时间除以五分钟(300秒)的提醒。
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
答案 1 :(得分: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);
答案 2 :(得分:-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>