简体   繁体   English

小时、分钟和秒的倒数计时器

[英]Countdown timer for hours, minutes, and seconds

How to set cookie for this count down timer?如何为这个倒数计时器设置 cookie? The cookie should prevent resetting timer while I am refreshing the page.当我刷新页面时,cookie 应该可以防止重置计时器。

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

The problem is if you save the time in cookie just before refresh and retrieve it after page loads it may not match the real current time because page may take arbitrary amount of time to refresh, 1st time it may be 1 sec 2nd time may be faster and take 0.5 sec due to factors like caching etc. for users on slower network it may be always more than 1-2 seconds. 问题是如果您在刷新之前将时间保存在 cookie 中并在页面加载后检索它,它可能与实际当前时间不匹配,因为页面可能需要任意时间来刷新,第一次可能是 1 秒第二次可能更快由于缓存等因素,需要 0.5 秒。对于较慢网络上的用户,它可能总是超过 1-2 秒。 So the time on the page will always lag and won't match the real current time after a few refreshes. 因此,页面上的时间将始终滞后,并且在几次刷新后与实际当前时间不匹配。

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看起来我错了浏览器在下载所有必需的资源之前不要刷新页面上已有的内容,因此您的计数器会继续运行并设置 cookie 直到一切就绪

Here is what i got to work这是我的工作

<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: Tried and tested the countdown survives page refresh and accurate even in heavy page throttling >10 seconds! PS:经过尝试和测试,即使在超过 10 秒的繁重页面节流下,倒计时也能保持页面刷新和准确!

If you don't want current time but any manual time entered you can always adjust the values to get the desired effect.如果您不想要当前时间而是任何手动输入的时间,您可以随时调整值以获得所需的效果。

I think you need to use document.cookie = newtime .我认为您需要使用document.cookie = newtime So every time when you assign newtime to element on the same time newtime should also be assigned to cookie so it may not be lost.所以每次当你为元素分配 newtime 时,同时 newtime 也应该分配给 cookie,这样它就不会丢失。

Simple:简单:

Let's assume you need 2 clocks, each with different duration time (if you need more than 2 clocks, or only one, just extrapolate the explanation).假设您需要 2 个时钟,每个时钟具有不同的持续时间(如果您需要 2 个以上的时钟,或者只需要一个,只需推断解释)。

  1. Set running and stopped clock styles:设置运行和停止时钟样式:

       .runningClock, stoppedClock
          {width:75px;
           color:white;           
           font-weight:bold;
           border:3px double white
          }
    
       .runningClock { background:#1ABB9C;  /* use your favorite green/turquoise */ }
       .stoppedClock { background:red; }
  1. Create each clock in HTML with an ID (I'm using DIV, but it can be a TD, a SPAN or other block object) [ignore extra spaces below, typed here to make code visible]:在 HTML 中创建每个带有 ID 的时钟(我使用的是 DIV,但它可以是 TD、SPAN 或其他块对象)[忽略下面的额外空格,在此处键入以使代码可见]:
  • < div id=clock1>< /div> <div id=clock1></div>
  • < div id=clock2>< /div> <div id=clock2></div>
  1. within your JS block, build these 2 functions:在你的 JS 块中,构建这两个函数:

    function Secs2Clock( numSecs ) { // converts # of seconds to a digital clock format )
        return ( parseInt( numSecs /3600 ).toString().padStart(2,"0") + ':' +
                 (parseInt( (numSecs /60) )%60).toString().padStart(2,"0") + ':' +
                 parseInt( numSecs %60 ).toString().padStart(2,"0") );
    }
    
    function runClock( oneClock, hours, minutes ) {
      var secs=hours*minutes*60;
              
      oneClock.className="runningClock"; // sets it to paint green, running
              
      var runningClock=setInterval( function() { //starts clock refreshing by second
         oneClock.innerHTML = Secs2Clock( secs );
    
         if ( secs>0 ) secs--  // single instruction if true, feel free to add curled brackets for readability
            else {
                oneClock.innerHTML="00:00:00";
                oneClock.className="stoppedClock";
                clearInterval( runningClock );
            }
    
        }, 1000     
      );
       
    }
  1. Within your main JS block (or your "BODY onLoad" function or wherever you want the clock[s] to launch), add this line for each clock (in this example, 2 different ones);在您的主要 JS 块(或您的“BODY onLoad”函数或您希望时钟 [s] 启动的任何地方)中,为每个时钟添加这一行(在本例中,2 个不同的); or else within the onClick action or whatever action (A HREF click, etc) where you want the specific clock(s) to start (in this example, this is part of the main JS code, to launch both clocks with different remaining times)或者在您希望特定时钟开始的 onClick 操作或任何操作(HREF 单击等)中(在此示例中,这是主要 JS 代码的一部分,以不同的剩余时间启动两个时钟)

    runClock( clock1, 1, 0 );   // will start as "01:00:00"
    runClock( clock2, 6, 30 );  // will start as "06:30:00"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM