【问题标题】:JavaScript Local Storage Second CounterJavaScript 本地存储第二个计数器
【发布时间】:2021-05-19 19:05:37
【问题描述】:

我的问题如下:是否可以使用本地存储创建第二个计数器?我的意思是你加载页面,计数器从 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>

【问题讨论】:

  • 是的,使用真实的参考时间,无论如何,一秒的 setInteval 真正持续一秒的可能性为零

标签: javascript html time local-storage counter


【解决方案1】:

这样吗?

<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
------------------------------------------------------------*/

【讨论】:

  • 还有一件事。我想做一个简单的条件,上面写着if(seconds == 5) {STOP_COUNTER},但我不知道该怎么做,因为我在本地存储方面并没有真正的经验。知道当计数器达到 5 时如何停止计数器吗?
  • @scrummy 我添加了if (seconds &gt;= 5) stopCounter()。 localStorage 非常简单 => developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
  • 最后一个问题,我保证。计数器达到 5 后,有什么方法可以完全停止或移除计数器?我的意思是你重新加载页面,它开始计数到 ​​5。在它达到 5 并重新加载页面后,计数器值仍然是 5,并且不会再继续计数。
  • @scrummy 啊!,好的,没问题,我已经为此更新了我的代码;)
  • @scrummy 绝对不是!只是我正处于我难得的好日子之一
【解决方案2】:
var el = document.getElementById('seconds-counter');

function incrementSeconds() {
    var counter = window.localStorage.getItem("counter") ?? 0;
    window.localStorage.setItem("counter", ++counter);
    el.innerText = counter;
}

var cancel = setInterval(incrementSeconds, 1000);

【讨论】:

    猜你喜欢
    • 2016-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多