同一网络会话中的永久计数器 [英] Perpetual counter within the same web session

查看:46
本文介绍了同一网络会话中的永久计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在网页上创建一个计数器,该计数器不会在同一用户会话内的每个不同页面视图上重新启动.当前使用此代码(对Praveen Kumar Purushothaman表示感谢(感谢),但是每次查看其他页面时,此计数器都会重置.

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>

推荐答案

我的建议是将变量存储到会话存储中.我在评论中添加了更多详细信息:

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);
  }
}

这篇关于同一网络会话中的永久计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆