问题
Trying to have a counter on a web page that does not restart on each different page view within the same user session. Currently using this code (thanks to Praveen Kumar Purushothaman) but this counter resets every time a different page is viewed.
setTimeout(start, 0);
var i = 0;
var num = document.getElementById("number");
function start() {
increase();
setInterval(increase, 1000);
}
function increase() {
if (i < 100000) {
i += 10.41;
num.innerText = i.toFixed(2);
}
}
<span id="number"></span>
回答1:
My suggestion is storing the variable into session storage. I have added more details in the comments:
setTimeout(start, 0);
// You're saving your current value here.
// Let's use localStorage. Set the i value if it doesn't exist for the first time.
if (!localStorage.getItem("i")) {
localStorage.setItem("i", 0);
}
var num = document.getElementById("number");
function start() {
increase();
setInterval(increase, 1000);
}
function increase() {
var i = localStorage.getItem("i");
if (i < 100000) {
i += 10.41;
// When you're making any changes, make changes to the localStorage too.
localStorage.setItem("i", i);
num.innerText = i.toFixed(2);
}
}
来源:https://stackoverflow.com/questions/64775260/perpetual-counter-within-the-same-web-session