我需要帮助来存储这个计时器倒计时的时间它运行正常但是当我按下刷新或浏览器后面时,计时器将重新启动它,如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>
在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>
在这里,我们应该将变量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");
},
}
}
);
})();