【问题标题】:Timer that keeps counting when navigating away from page离开页面时不断计数的计时器
【发布时间】:2015-12-11 01:30:32
【问题描述】:

我有一个计时器,可以在访问特定页面后进行倒计时。即使有人转到其他页面,我也需要此计时器继续计数,并保持计数的时间以在他们返回触发它的原始页面时将其显示在屏幕上。

我的代码是

<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 不太了解,之前在多个页面之间共享变量也没有任何运气。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    将开始时间填充到 cookie(或本地存储,任何永久性的)中,并使用该开始时间与当前时间之间的差值作为计时器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      • 2010-09-11
      • 1970-01-01
      相关资源
      最近更新 更多