[英]how to store timer in localstorage and resume on page reload
I have a timer on my page that starts counting from the moment the page is loaded, shows it in minutes and seconds.我的页面上有一个计时器,它从页面加载的那一刻开始计时,以分钟和秒为单位显示。 There is also a save button that saves this time, and when we reload the page, the timer should start counting from the time we saved.
还有一个保存这次时间的保存按钮,当我们重新加载页面时,计时器应该从我们保存的时间开始计时。 But on reboot it writes NAN: NAN.
但是在重新启动时它会写 NAN:NAN。 How can I save and resume timing correctly?
如何正确保存和恢复计时?
let timerInterval;
let timerStart;
let time = 0;
function updateTime() {
time++;
let mins = parseInt(time / 60);
let secs = time % 60;
if(mins < 10) {
mins = '0' + String(mins);
}
if(secs < 10) {
secs = '0' + String(secs);
}
document.querySelector('#timespan').innerHTML = `${mins}:${secs}`;
}
function startTimer() {
timerInterval = setInterval(updateTime, 1000);
time = 0;
timerStart = true;
};
function stopTimer() {
clearInterval(timerInterval);
time = 0;
timerStart = false;
}
document.querySelector('.save-btn').addEventListener('click', () => {
localStorage.setItem('currentTime', document.querySelector('#timespan').innerHTML);
}
window.addEventListener('load', () => {
document.querySelector('#timespan').innerHTML = localStorage.getItem('currentTime');
}, false );
You need to parse localStorage
content to hydrate your global time
variable before after you call startTimer
(which is not shown in the code you posted).您需要在调用
startTimer
之后解析localStorage
内容以补充全局time
变量(您发布的代码中未显示)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.