导航离开页面时保持计数的计时器

时间:2015-12-10 17:13:21

标签: javascript

我有一个计时器,一旦访问特定页面就倒计时。即使有人去了另一个页面,我也需要这个计时器来保持计数,并且当他们返回到触发它的原始页面时,保持计时以在屏幕上显示它。

我的代码是

<script>
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("test9_cookie");

if(cook==""){
//cookie not found, so set seconds=60
var seconds = '<?php echo OFFERTIME ?>';
}else{
seconds = cook;
console.log(cook);
}

// init var
var timeout = 0;
// end init var
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
    remainingSeconds = "0" + remainingSeconds; 
}
//store seconds to cookie
setCookie("test9_cookie",seconds,1); //here 1 is expiry days
document.getElementById('countdown').innerHTML = minutes + ":" +    remainingSeconds;
if (seconds == 0) {
    clearInterval(countdownTimer);
    timeout = 1;
    sessionStorage.setItem('nothanks', 1);
  document.getElementById('timed-over').style.display = "block";
  $("#timed-over").delay(4800).fadeOut(300);
  document.getElementById('timed-container').style.display = "none";

} else {    
    seconds--;
}
}

var countdownTimer = setInterval(secondPassed, 1000);

//localStorage.removeItem('timedpid') //to delete localstorage during testing
function checktaken(){
if(timeout===1) {
//do nothing as expired
}else if(localStorage.getItem('timedpid')) {
   var storedpid = localStorage.getItem('timedpid')
   var currentpid =<?php echo json_encode($time_limited_pid); ?>;
   if (storedpid !== currentpid) {
        var showOffer = document.querySelector("#timed-container");
        showOffer.style.display = "block";
   }
   }else if(sessionStorage.getItem('nothanks')) {
   // do nothing as offer not wanted 
   }else{
    var showOffer = document.querySelector("#timed-container");
    showOffer.style.display = "block";
   }
}
setInterval('checktaken()',1); 
</script>

当脚本打开的页面被导航离开时,有没有办法让原始代码继续计数?

如果没有,解决方案是将部分脚本移动到标题,并仅在特定页面上加载。这样做意味着必须将标头中的脚本中的var传递给另一个文件中的脚本。我之前并没有太多关于javascript的信息,并且之前没有任何运气在多个页面之间共享变量。

1 个答案:

答案 0 :(得分:2)

将开始时间填入cookie(或本地存储,任何永久存储)并使用开始时间与计时器当前时间之间的差异。