我需要帮助存储此计时器倒计时的时间,它运行正常,但是当我按刷新或浏览器返回时,计时器将像15:00一样重新启动计时器,那么如果我启动计时器,则时间为9:00按刷新,它将回到15:00。
(function() {
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond(x) {
return ~~(x / 60) + ":" + (x % 60 < 10 ? "0" : "") + x % 60;
}
function setTimer(remain, actions) {
var action;
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
if (action = actions[remain]) {
action();
}
if (remain > 0) {
remain -= 1;
setTimeout(arguments.callee, 1000);
}
})(); // End countdown
}
setTimer(900, {
120: function() {
display("notifier", "Just 1 minute to go");
},
50: function() {
display("notifier", "50 seconds left");
},
}
}
);
})();
<span id="notifier"></span>
答案 0 :(得分:0)
在JS中-请注意我将localStorage放在哪里(该代码未在代码段中运行) 我还修复了已发布代码中的错误
(function() {
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond(x) {
return ~~(x / 60) + ":" + (x % 60 < 10 ? "0" : "") + x % 60;
}
function setTimer(remain, actions) {
var action;
(function countdown() {
// add localStorage.setItem("countdown",remain)
display("countdown", toMinuteAndSecond(remain));
if (action = actions[remain]) {
action();
}
if (remain > 0) {
remain -= 1;
setTimeout(arguments.callee, 1000);
}
else display("countdown","Done");
})(); // End countdown
}
setTimer(30, { // change 30 to +localStorage.getItem("countdown") || 30;
20: function() {
display("countdown", "Just 20 seconds to go");
},
10: function() {
display("countdown", "10 seconds left");
},
});
})();
<span id="countdown"></span>
答案 1 :(得分:-1)
在这里,我们应该将变量remain
保留在本地存储中。即使刷新后,本地存储中的变量仍然可用。
附上您期望的代码。
(function() {
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond(x) {
return ~~(x / 60) + ":" + (x % 60 < 10 ? "0" : "") + x % 60;
}
function setTimer(remain, actions) {
var action;
localStorage.remain = remain;
(function countdown() {
remain = localStorage.remain;
display("countdown", toMinuteAndSecond(remain));
if (action = actions[remain]) {
action();
}
if (remain > 0) {
localStorage.remain -= 1;
setTimeout(arguments.callee, 1000);
}
})(); // End countdown
}
setTimer(900, {
120: function() {
display("notifier", "Just 1 minute to go");
},
50: function() {
display("notifier", "50 seconds left");
},
}
}
);
})();