【问题标题】:JS countdown timer with cookie issues带有 cookie 问题的 JS 倒数计时器
【发布时间】:2013-05-16 03:41:20
【问题描述】:

我们有一个 24 小时倒计时。问题是,每当刷新页面时,计时器就会重新启动。我们如何创建一个 cookie,以便它不会为同一个用户/刷新时重新启动?如果 if 降到 0 又会重新启动?

我们目前所拥有的:

<script type = "text/javascript">
var totalSeconds;
function initiate(seconds) 
{
  totalSeconds = parseInt(seconds);
  setInterval("timeUpdate()", 1000); 
}
function timeUpdate() 
{
   var seconds = totalSeconds;
   if(seconds > 0) 
   {
          totalSeconds--; 
          var hours= Math.floor(seconds/3600);
          seconds %= 3600;
          var minutes = Math.floor(seconds/60);
          seconds %= 60;
          var timeIs = ((hours < 10) ? "0" : "") + hours + ":" + ((minutes < 10) ? "0" : "") + minutes + ":" + ((seconds < 10) ? "0" : "") + seconds;
          document.getElementById("timeLeft").innerHTML = "" + timeIs;
   }
   else 
   {
          document.getElementById("timeLeft").innerHTML = '';
          document.getElementById("message").innerHTML = '';
   }
}
initiate(24 * 60 * 60);
</script>

【问题讨论】:

    标签: javascript counter countdown


    【解决方案1】:
       document.cookie="name=" + cookievalue;
       alert("Setting Cookies : " + "name=" + cookievalue );
    

    SEE HERE

    【讨论】:

    • 我该如何使用它?在哪里?你能展示如何将这些代码片段放在页面上吗?感谢您的帮助!
    • 你可以在链接中看到一个例子
    【解决方案2】:

    首先我们需要有设置和读取cookies的函数。为此,请使用此答案中给出的功能How do I create and read a value from cookie?

    所以,我们的代码中有两个函数createCookiesetCookie

    现在在页面加载时设置并获取 cookie,如下所示

    var
        //Get time started
        timeStarted = getCookie('timeStarted'),
        //To store total seconds left
        totalSeconds,
        //Current Time
        currentTime = parseInt(new Date()/1000),
        //Timer Length
        timerLength = 24 * 60 * 60;
    
    if(timeStarted == "") {
    
        //Time not yet started. Start now.
        createCookie('timeStarted', currentTime, 365);
    
        //We started time just now. So, we have full timer length remaining
        totalSeconds = timerLength;
    
    } else {
    
        //Calculate total seconds remaining
        totalSeconds = timerLength - (currentTime - timeStarted)%(timerLength);
    }
    

    现在初始化如下所示

    initialize(totalSeconds);
    

    您的两个功能都可以正常工作并保留它们。

    我使用 365 天作为 cookie 期限。我们只需要开始时间。

    根据您的要求更改代码。

    如果您需要有关此代码的任何说明,请告诉我。

    【讨论】:

    • 谢谢,但我是这方面的新手。我在哪里把初始化(totalSeconds);到底是什么?
    • 我尝试添加第一段代码和 cookie 代码,并按照您上面所说的设置和获取,然后 body onload initialize(totalSeconds);但计时器在页面刷新时重新启动。您能按照我应该使用的方式将所有代码块放在一起吗?感谢您的帮助!
    • 希望您正在从服务器运行文件,并且在浏览器中启用了 cookie。从服务器运行的文件只能使用 cookie。你可以把 initialize(totalSeconds);在末尾。所以,有点像,所有函数都先出现,然后是给定的代码,然后初始化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多