gpt4 book ai didi

javascript - 设置倒计时/计时器在重置后继续或刷新页面后不重置

转载 作者:行者123 更新时间:2023-11-30 15:19:28 25 4
gpt4 key购买 nike

我正在尝试获得一个倒计时/计时器,它在刷新页面后继续,而不是从头开始重新启动。我使用过 JavaScript,但它会在重新加载页面时重置。

var timer2 = "1:30";
$('.countdown').html(timer2);

var interval = setInterval(function() {

var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0){
clearInterval(interval);
$('input[name=ansSubmit]').trigger("click");
}else{
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
}
}, 1000);

计时器会一直持续到用户点击提交,但如果用户重新加载页面,是否可以使用 PHP 或 JavaScript 自动恢复计时?

最佳答案

只需使用浏览器Window.localStorage (或 sessionStorage,如果它更合适的话)。

<div class="countdown"></div>
<button style="display:none">FINISH!!!</button>
<script>
$(document).ready(function() {
var timer2 = localStorage.getItem('timer');
if(timer2 === null) timer2 = "1:30";
$('.countdown').html(timer2);

var interval = setInterval(function() {
var timer = timer2.split(':');
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0){
clearInterval(interval);
localStorage.removeItem('timer');
$('button').show();
}else{
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
$('.countdown').html(minutes + ':' + seconds);
timer2 = minutes + ':' + seconds;
localStorage.setItem('timer',timer2);
}
}, 1000);
});
</script>

关于javascript - 设置倒计时/计时器在重置后继续或刷新页面后不重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43966734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com