我正在学习倒计时,我在互联网上找到了一个指南。但当页面关闭倒计时停止,如果我再次打开页面倒计时再次运行,我想让倒计时继续运行,即使页面关闭 http://jsfiddle.net/FnsY4/
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
//check existing cookie
cook=getCookie("my_cookie");
if(cook==""){
//cookie not found, so set seconds=60
var seconds = 60;
}else{
seconds = cook;
console.log(cook);
}
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
//store seconds to cookie
setCookie("my_cookie",seconds,5); //here 5 is expiry days
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval(secondPassed, 1000);
<span id="countdown" class="timer"></span>
答案 0 :(得分:1)
如果您希望倒计时即使关闭标签也有效,则您必须使用两个(或更多)选项重新考虑它: