gpt4 book ai didi

JavaScript 本地存储秒计数器

转载 作者:行者123 更新时间:2023-12-04 08:05:42 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com