小时,分钟和秒的倒计时定时器 [英] Countdown timer for hours, minutes, and seconds

查看:195
本文介绍了小时,分钟和秒的倒计时定时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设定这个倒数计时器的Cookie?
在刷新页面时,cookie应该阻止重置计时器。

How to set cookie for this count down timer? The cookie should prevent resetting timer while I am refreshing the page.

<div id="hms">02:00:00</div>
<script type="text/javascript">
    function count() {
        var startTime = document.getElementById('hms').innerHTML;
        var pieces = startTime.split(':');
        var time = new Date();
        time.setHours(pieces[0]);
        time.setMinutes(pieces[1]);
        time.setSeconds(pieces[2]);
        var timedif = new Date(time.valueOf() - 1000);
        var newtime = timedif.toTimeString().split(' ')[0];
        document.getElementById('hms').innerHTML = newtime;
        setTimeout(count,1000);
    }
    count();
</script>


推荐答案

问题是如果你节省时间在cookie刚刚刷新之前,并在页面加载后检索它可能不匹配实际当前时间,因为页面可能需要任意量的时间刷新,第一次它可能是1秒第二次可能更快,需要0.5秒由于像缓存等用户在较慢的网络上可能总是超过1-2秒。所以页面上的时间将总是滞后,并且在几次刷新后将不会匹配实际的当前时间。

看起来我错了浏览器, t刷新页面上的内容,直到所有必需的资源下载,所以您的计数器持续运行以及设置cookie,直到它准备好

Looks like i was wrong browser don't refresh the content already on the page until all required resources are downloaded so your counter keeps going as well as setting cookies until its all ready

这是我要工作

<html>
<body>
<div id="hms">02:00:00</div>
</body>

<script>
var startTime;
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
} // credits kirlich @http://stackoverflow.com/questions/10730362/get-cookie-by-name

function count() {
 if(typeof getCookie('remaining')!= 'undefined')
 {
   startTime = getCookie('remaining');
 }
 else if(document.getElementById('hms').innerHTML.trim()!='')
 {
   startTime = document.getElementById('hms').innerHTML;
 }
 else
 {
  var d = new Date(); 
  var h=d.getHours(); 
  var m=d.getMinutes();
  var s=d.getSeconds();
  startTime = h+':'+m+':'+s;
  //OR
  startTime  = d.toTimeString().split(" ")[0]
 }

 var pieces = startTime.split(":");
 var time = new Date();
 time.setHours(pieces[0]);
 time.setMinutes(pieces[1]);
 time.setSeconds(pieces[2]);
 var timediff = new Date(time.valueOf()-1000)
 var newtime = timediff.toTimeString().split(" ")[0];
 document.getElementById('hms').innerHTML=newtime ;
 document.cookie = "remaining="+newtime;
 setTimeout(count,1000);
}
count();
</script>

</html>

PS:尝试并测试了倒计时,重页面调节> 10秒!

PS: Tried and tested the countdown survives page refresh and accurate even in heavy page throttling >10 seconds!

如果您不想要当前时间,但输入任何手动时间,您总是可以调整值以获得所需的效果。

If you don't want current time but any manual time entered you can always adjust the values to get the desired effect.

这篇关于小时,分钟和秒的倒计时定时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆