JS倒计时器与cookie问题

时间:2013-05-16 03:41:21

标签: javascript counter countdown

我们有24小时倒数计时器。问题是,每当刷新页面时,计时器重新启动。我们如何创建一个cookie,以便在刷新时不会为同一个用户重启?如果再次重新启动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>

2 个答案:

答案 0 :(得分:0)

   document.cookie="name=" + cookievalue;
   alert("Setting Cookies : " + "name=" + cookievalue );

SEE HERE

答案 1 :(得分:0)

首先,我们需要具有设置和读取cookie的功能。为此,请使用此答案中给出的函数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期间。我们只需要开始时间。

根据您的要求更改代码。

如果您需要有关此代码的任何说明,请与我们联系。

相关问题