我正在尝试在 Start/Stop 计时器中检索 localStorage
数据。我的目标是让计时器在页面加载时自动启动,但当用户离开并稍后返回时(页面刷新),计时器将从它停止的地方恢复。
我快要让它工作了..但在每次页面刷新后它又开始回到 00:00:00
。
我创建了一个带有 3 秒延迟的 setTimeout
函数来说明其中的一些是有效的。
非常感谢任何能帮助我走上正轨的人。
HTML
<!-- Timer -->
<div class="time-wrapper">
<strong>Time</strong>
<span id="time-total">00:00:00</span>
</div>
<!-- Controls -->
<div class="button-wrapper">
<button id="start-timer" class="button">Start</button>
<button id="pause-timer" class="button">Pause</button>
</div>
JS (带有 EasyTimer.js 插件)
/* Create Timer
********************************/
var timer = new Timer();
var timeTotal = $('#time-total'),
timeKey = 'time_stored',
timeStored = localStorage.getItem(timeKey);
// Update Event
timer.addEventListener('secondsUpdated', function (e) {
$(timeTotal).html(timer.getTimeValues().toString());
});
// Started Event
timer.addEventListener('started', function (e) {
$(timeTotal).html(timer.getTimeValues().toString());
});
// Start Timer
$('#start-timer').click(function () { timer.start(); });
$('#pause-timer').click(function () { timer.pause(); });
/* When page loads
********************************/
$(document).ready(function() {
setInterval(function() {
localStorage.setItem(timeKey, timeTotal.text());
}, 500);
if (timeStored) {
timeTotal.text(timeStored);
}
setTimeout(function() {
$('#start-timer').click();
timer.start();
}, 3000);
});
最佳答案
您可以在启动计时器时设置默认值 - 请参阅下面的示例。您可能需要相应地调整 Start 按钮的功能,因为它还会调用计时器的 start() 方法。请注意,我为您的 localStorage 使用了不同的键(以防万一您的浏览器中已经有一个设置值)并且我只存储秒数,每次触发事件 secondsUpdated
时秒数都会增加。不需要您自己的 setInterval,因为您可以使用上述事件触发的计时器间隔。
var timer = new Timer();
var timeTotal = $('#time-total'),
timeKey = 'time_stored_seconds',
timeStored = localStorage.getItem(timeKey);
// Update Event
timer.addEventListener('secondsUpdated', function (e) {
var newValue = parseInt(localStorage.getItem(timeKey) | 0)+1
localStorage.setItem(timeKey, newValue);
$(timeTotal).html(timer.getTimeValues().toString());
});
// Started Event
timer.addEventListener('started', function (e) {
$(timeTotal).html(timer.getTimeValues().toString());
});
// Start Timer
$('#start-timer').click(function () { timer.start(); });
$('#pause-timer').click(function () { timer.pause(); });
/* When page loads
********************************/
$(document).ready(function() {
if (timeStored) {
timeTotal.text(timeStored);
}else{
localStorage.setItem(timeKey, 0);
timeStored = 0
}
timer.start({ precision: 'seconds', startValues: {seconds: parseInt(timeStored)}});
});
关于javascript - 在 "start/stop"计时器中检索 localStorage 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47750656/