JavaScript 本地存储秒计数器

标签 javascript html time local-storage counter

我的问题如下:是否可以使用本地存储创建第二个计数器?我的意思是你加载页面,计数器从 1 开始一个一个地计数。您在 5 秒重新加载页面,计数器不会重置,而是从 5 继续计数。这可能吗?

我有一个带有简单秒计数器的代码,但我不知道如何让它与本地存储一起工作

var seconds = 0;
var el = document.getElementById('seconds-counter');

function incrementSeconds() {
seconds += 1;
el.innerText = seconds;
}



var cancel = setInterval(incrementSeconds, 1000);
<div id='seconds-counter'> </div>

最佳答案

这样吗?

<div id="seconds-counter">_</div>
<!-- button id="bt-stop-counter"> stop counter </button -->
const 
  counterLimit  = 5  // <-- your counter limit value....
, div_s_counter = document.querySelector('#seconds-counter')
, btStopCounter = document.querySelector('#bt-stop-counter')
, timeRef_ls    = localStorage.getItem('counterVal') || 0
, timeRef       = (new Date()) - (timeRef_ls * 1000)
, CounterIntv   = setInterval(() =>
  {
  let seconds = Math.floor(((new Date()) - timeRef) / 1000)

  if (seconds >= counterLimit )  // stopCounter()
    {
    div_s_counter.textContent = seconds = counterLimit
    clearInterval( CounterIntv ) 
    }
  div_s_counter.textContent = seconds
  localStorage.setItem('counterVal', seconds.toString(10))
  }
  , 500)
;
div_s_counter.textContent = timeRef_ls

/* disable counter reset ------------------------------------
  {
  clearInterval( CounterIntv )          // to stop the counter
  localStorage.removeItem('counterVal') // remove the counter
  }

btStopCounter.onclick = stopCounter
------------------------------------------------------------*/

关于JavaScript 本地存储秒计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66232692/

相关文章:

python - 将 float 转换为日期时间时参数无效

javascript - 在鼠标悬停时更改按钮文本,调整整个按钮的大小

javascript - Websocket 帧大小限制

html - 不同浏览器上的文本溢出较少

html - 无法加载背景图片

mysql - 如何根据耗时(带有时间字段)进行选择

time - 如何在一天中的特定时间运行 cypress 测试?

javascript - 在 Canvas 中制作波浪并制作动画

javascript - GraphQL:不可为空的数组/列表

html - paypal API 是否支持我的应用程序上的用户对用户付款?