以下脚本进行倒计时,直到达到设定的数字(在本例中为76),然后再次开始倒计时,依此类推。更新页面时,除非localStorage过期,否则不会重置倒数计时。
我希望倒数计时到76时停止并且不重新开始计数。直到localStorage过期。请问我该怎么做?
<div id="divCounter"></div>
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (+max - +min)) + +min;
if (localStorage.getItem("counter")) {
if (localStorage.getItem("counter") >= 1000000000) { // Duration of localStorage
var value = random;
} else {
var value = localStorage.getItem("counter");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var counter = function () {
if (value <= 76) { // End count down. <= or >=
localStorage.setItem("counter", random);
value = random;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("counter", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function () {
counter();
}, 1000); // speed count
答案 0 :(得分:0)
此代码有很多问题,但是鉴于这里的情况,您需要在值<= 76时调用clearInterval(interval)来阻止localStorage再次更改。
答案 1 :(得分:0)
这是我对您意图的最佳猜测:
// 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);
这正确吗?