[英]Prevent timer reset on page refresh
我有麻烦了。 我在java脚本中做了倒数计时器代码但是当我刷新页面计时器被重置所以如何解决这个问题
这是我的代码。
var min = 1; var sec = 59; var timer; var timeon = 0; function ActivateTimer() { if (!timeon) { timeon = 1; Timer(); } } function Timer() { var _time = min + ":" + sec; document.getElementById("Label1").innerHTML = _time; if (_time != "0:0") { if (sec == 0) { min = min - 1; sec = 59; } else { sec = sec - 1; } timer = setTimeout("Timer()", 1000); } else { window.location.href = "page2.html"; } }
<BODY onload="Timer();"> <div id="Label1"> </div> </BODY>
这种方法使用 localStorage 并且不会在页面刷新时暂停或重置计时器。
<p id="demo"></p>
<script>
var time = 30; // This is the time allowed
var saved_countdown = localStorage.getItem('saved_countdown');
if(saved_countdown == null) {
// Set the time we're counting down to using the time allowed
var new_countdown = new Date().getTime() + (time + 2) * 1000;
time = new_countdown;
localStorage.setItem('saved_countdown', new_countdown);
} else {
time = saved_countdown;
}
// Update the count down every 1 second
var x = setInterval(() => {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the allowed time
var distance = time - now;
// Time counter
var counter = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = counter + " s";
// If the count down is over, write some text
if (counter <= 0) {
clearInterval(x);
localStorage.removeItem('saved_countdown');
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Javascript 是客户端的。 它将在重新加载或任何其他事情时重置。
您的问题的一个简单解决方案可能是 html5 存储或会话存储。
https://www.w3schools.com/html/html5_webstorage.asp
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
希望这有帮助!
您正在寻找window.localStorage
。 这样的事情应该工作:
<script language="javascript" type="text/javascript">
var min = 1;
var sec = 59;
var timer;
var timeon = 0;
function ActivateTimer() {
//Don't activate if we've elapsed.
if(window.localStorage.getItem('elapsed') != null)
return;
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = min + ":" + sec;
document.getElementById("Label1").innerHTML =_time;
if (_time != "0:0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
window.localStorage.setItem('elapsed', true);
window.location.href = "page2.html";
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.