Perpetual counter within the same web session

对着背影说爱祢 提交于 2021-01-05 12:47:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!