我试图存储我的脚本,从23,000开始计算数字,总是继续显示它"生活"并始终使用Web存储计数。我已经尝试过实现这一点,到目前为止,我似乎无法让它发挥作用。什么是最好的解决方案,让这个工作和功能总是计数,即使刷新等? I've included my JS Fiddle以及下面的代码。任何帮助都很感激!!
编辑:澄清..我试图拥有一个"直播"无论你什么时候去页面,刷新它,无论如何,反击总是会进行。无论我的脚本如何,它总是会变得越来越大。但是,每次刷新它都会以23,000开始。
HTML
<span id="liveNumbers">23,000</span>
JS
if(typeof(Storage)!=="undefined")
{
setInterval(function(){
random = (Math.floor((Math.random()*2)+1));
var plus = Math.random() < 0.5 ? 1 : 1;
random = random * plus;
currentnumber = document.getElementById('liveNumbers');
var curnum = parseInt(currentnumber.innerHTML.replace(",",""));
document.getElementById('liveNumbers').innerHTML =
commaSeparateNumber(curnum + random);
}, 3000);
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}
}
else
{
// Sorry! No Web Storage support..
}
答案 0 :(得分:1)
这是我的尝试:fiddle
逻辑:
localStorage
数据)时,计数器将重置为23000
。lastSessionEnd
)一起存储。randomRange
函数并从上一个会话添加到存储的计数器。以下是代码:
if(window.localStorage) {
//configs
var updateInterval = 3000; //ms
function randomRange() {
return Math.floor(Math.random()*3)+1; // [1..3] range
}
var counter = +localStorage.getItem('counter');
if (!counter) { //first load
counter = 23000;
} else { //simulate randomness that would have happened while the user was away from the page
var lastSessionEnd = +localStorage.getItem('lastSessionEnd');
for(var l = Math.floor((getUnixTimeStamp() - lastSessionEnd)*1000/updateInterval); l--;) {
counter += randomRange();
}
}
var liveNumbers = document.getElementById('liveNumbers'); //cache DOM query
function refreshDisplay() {
liveNumbers.innerHTML = commaSeparateNumber(counter);
}
refreshDisplay();
setInterval(function() {
counter += randomRange();
refreshDisplay();
}, updateInterval);
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}
function getUnixTimeStamp() {
return Math.floor(Date.now()/1000);
}
window.addEventListener('beforeunload', function() {
localStorage.setItem('counter', counter);
localStorage.setItem('lastSessionEnd', getUnixTimeStamp());
});
} else {
// Sorry! No Web Storage support..
}
注意:这不完美,以下是警告:
localStorage
很容易破解。不要将它用于重要的事情。localStorage
API时,如果用户在多个浏览器(或多个计算机/设备)中打开页面,则每个浏览器将具有不同的计数器。此外,清洁所有个人数据将重置柜台。