2 回答

TA貢獻(xiàn)1796條經(jīng)驗 獲得超7個贊
這段代碼有很多問題,但考慮到這里的情況,您需要在 value <= 76 時調(diào)用 clearInterval(interval) 以阻止 localStorage 在該點再次更改。

TA貢獻(xiàn)1831條經(jīng)驗 獲得超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);
這樣對嗎?
添加回答
舉報