在计时器中检索本地存储数据"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() 方法。请注意,我为您的 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)}});
}); 

相关内容

最新更新