javascript javascript倒计时到下一个真正的5分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16156832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript countdown to next real 5 minutes
提问by dj_boy
I need to create a javascript timer that will count down to the next 5 minutes. For example let's say the time is 00:07:30, the time will say 02:30 if the time is 15:42:00 the timer will say 03:00 I can't really think of any good way to du this. thank you.
我需要创建一个 javascript 计时器,它会倒计时到接下来的 5 分钟。例如,假设时间是 00:07:30,时间会说 02:30 如果时间是 15:42:00 计时器会说 03:00 我真的想不出有什么好办法来杜绝这个。谢谢。
回答by Mark Ni
There are many ways to do this. My idea is to find out the reminder of current time divide by five minutes (300 seconds).
有很多方法可以做到这一点。我的想法是找出当前时间除以五分钟(300秒)的提醒。
Demo : http://jsfiddle.net/txwsj/
演示: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
回答by Raghav Malik
Instead you could try using window.setInterval()
like this:
相反,您可以尝试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);
回答by Raghav Malik
If you want to do a timer on your webpage, you can try to use something like this:
如果你想在你的网页上做一个计时器,你可以尝试使用这样的东西:
<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>