2 回答

TA贡献1796条经验 获得超7个赞
这段代码有很多问题,但考虑到这里的情况,您需要在 value <= 76 时调用 clearInterval(interval) 以阻止 localStorage 在该点再次更改。

TA贡献1831条经验 获得超9个赞
这是我对您意图的最佳猜测:
// If there's a count in localStorage but it is expired then
// set value to a random between 80 and 85
// else
// set value to the count in localStorage
// Display the count in a div and decrease it by 1 every second.
// If the count falls below 76 then
// stop counting down and
// reset the localStorage counter to the random value
const min = 80;
const max = 85;
const stopValue = 76;
const duration = 1000000000;
const rnd = Math.floor(Math.random() * (max - min)) + min;
const counter = () => {
const lsCounter = localStorage.getItem('counter');
let retval;
if(lsCounter && lsCounter <= duration){
retval = lsCounter - 1;
if(lsCounter <= stopValue){
clearInterval(interval);
retval = rnd;
}
}else{
retval = rnd;
}
localStorage.setItem('counter', retval);
document.getElementById('divCounter').innerHTML = retval;
}
let interval = setInterval(function () {
counter();
}, 1000);
这样对吗?
添加回答
举报