简体   繁体   English

即使在“另一页”或“浏览器刷新”中,如何让 setInterval countUp 计时器继续计数?

[英]How Can I make setInterval countUp timer keep counting even in “Another Page” or “browser refresh”?

i try to create some "visitor CountUp timer" on my header webpage.我尝试在我的 header 网页上创建一些“访客计数计时器”。 However when I select another tab, the timer is restart again from 00:00:00.但是,当我 select 另一个选项卡时,计时器从 00:00:00 再次重新启动。 Is there any solution to make it keep counting even in "Another Page" or "browser refresh"?即使在“另一页”或“浏览器刷新”中,是否有任何解决方案让它继续计数? I am not sure how to add sessionStorage into my current code.我不确定如何将sessionStorage添加到我当前的代码中。

Anyone willing to lend a hand on this?有人愿意为此提供帮助吗?

Thanks谢谢

 var sec = 0; function pad ( val ) { return val > 9? val: "0" + val; } setInterval( function(){ document.getElementById("seconds").innerHTML=pad(++sec%60); document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10)); document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10)); }, 1000);
 <span id="hours">00</span>:<span id="minutes">00</span>:<span id="seconds">00</span>

Your solution is using localstorage:您的解决方案是使用本地存储:

      var sec = 0;
      tmpSec = localStorage.getItem('secs')
      if (tmpSec != null) {
        sec = parseInt(tmpSec,10);
      }
      function pad ( val ) { return val > 9 ? val : "0" + val; }
      setInterval( function(){
        ++sec
        localStorage.setItem('secs', sec)
        document.getElementById("seconds").innerHTML=pad(sec%60);
        document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10));
        document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10));
      }, 1000);

Here is an example of interval which saved in localStorage https://github.com/syronz/micro-games/blob/master/02%20idle%20game/progress.html这是保存在 localStorage https://github.com/syronz/micro-games/blob/master/02%20idle%20game/progress.html中的间隔示例

var sec = 0;

that is going to reset your timer each time it is run.这将在每次运行时重置您的计时器。

But instead code it this way:但改为这样编码:

sessionStorage.sec = "0"; // only execute this when you want to reset your counter.

setInterval( function(){
  var sec = parseInt(sessionStorage.sec); 
  sec++;
  sessionStorage.sec = sec.toString();
  document.getElementById("seconds").innerHTML=pad(sec%60);
  document.getElementById("minutes").innerHTML=pad(parseInt(sec/60%60,10));
  document.getElementById("hours").innerHTML=pad(parseInt(sec/3600%60,10));
}, 1000);

You could add a query to the URL and then redirect to another URL with this query:您可以向 URL 添加查询,然后使用此查询重定向到另一个 URL:

window.location.href += "?end=someTime"

Then you could set the timer to have this as the end:然后你可以设置计时器以结束:

var url = new URL(window.location.href);
var end = url.searchParams.get("end");
doSomething(end);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM