我正在尝试使用一个永远不会停止的计数器,即使用户离开页面也是如此。我希望它能够连续工作,但我不知道如何做到这一点。目前,我有一个计数器,当用户在页面上时,即使用户更新它,它也会继续计数,但当用户离开时,它永远不会继续计数。
我该怎么做或者你可以推荐我什么教程?
我在这里得到了这个代码: Continual counter regardless of page refresh
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
$(".count").html(counter);
++counter;
localStorage.setItem('counts',counter);
}, 1000);
最佳答案
如果您每秒递增计数器,为什么不只存储用户首次访问该网站的时间戳并从当前时间戳中扣除它。
请注意,使用 localStorage()
不适用于 StackOverflow 片段或 JS fiddle,但您可以在这里看到它:https://js.do/code/271017
if(localStorage.getItem('start')===null)
{
localStorage.setItem('start',new Date().getTime());
}
setInterval(function () {
var t = new Date().getTime();
var s = localStorage.getItem('start');
$(".count").html(Math.round((t-s)/1000));
}, 1000);
<p class="count"></p>
这不会以任何方式使用 Laravel。如果用户使用 Laravel 登录到您的网站,您可以将开始时间存储在数据库中,以避免用户通过清除 cookie 来重置计数器。
关于javascript - 持续工作计数器 Laravel - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861371/