【发布时间】:2018-02-28 23:26:47
【问题描述】:
我的网页应该显示一个倒数计时器,现在设置为 1 小时。我想将倒计时存储在 cookie 中,这样即使我离开页面,计时器也会继续倒计时。我是在 javascript 中使用 cookie 的初学者,所以我真的需要一些帮助来解决我在这里做错的事情。
这是我的html代码
<b id="timer">00:00:00</b><br>
<button id="start">Start</button>
<button id="stop" hidden>Stop</button>
Javascript
var counter=0;
var timeleft=3600;
//function that returns countdown format 00:00:00
function convertSeconds(s){
var hr=Math.floor(s/3600);
var min=Math.floor(s/60%60);
var sec=s%60;
return ("0" + hr).slice(-2) + ':' + ("0" + min).slice(-2) + ':' + ("0" + sec).slice(-2);
}
//cookie expire time variable set to 1hr
var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
var cd = document.getElementById("timer");
if(document.cookie.length != 0){
var carray = document.cookie.split("=");
cd.innerHTML=carray[1]; //should display initial countdown duration before btnstart is clicked
function timeIt(){ //function that displays the dynamic countdown timer
counter++;
cd.innerHTML=carray[1];
}
}
var btnstart = document.getElementById("start");
var btnstop = document.getElementById("stop");
//starts countdown when btnstart clicked
btnstart.onclick = function()
{
//storing the countdown format to a cookie and setting expire time to 1hour
document.cookie = "cdanim=" + convertSeconds(timeleft-counter); + ";expires=" + now.toUTCString();
setInterval(timeIt, 1000); //starts the countdown
btnstart.hidden=true;
btnstop.hidden=false;
}
现在它显示一些我不知道它来自哪里的随机文本,而不是显示倒计时本身。 carray[1] 应该返回 1:00:00 但它不是。请帮忙。
【问题讨论】:
标签: javascript cookies countdown