gpt4 book ai didi

javascript - 希望 javascript 倒计时即使在刷新后也能从原来的位置继续

转载 作者:行者123 更新时间:2023-12-03 04:39:50 29 4
gpt4 key购买 nike

我正在使用下面的代码设计一个 3 小时的 JavaScript 倒计时

<div id="timer"></div>
<script type="text/javascript">
var count = 10800;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second

function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}

var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;

document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>

但我在这里遇到的唯一问题是,每当我刷新页面时,倒计时都会重新开始。我希望它从停止的地方恢复。

最佳答案

您需要将数据存储到某种持久存储方法中,例如cookie、浏览器localStorage ,或将数据写入外部数据源(例如通过 API 的数据库)。否则, session 数据会在浏览器刷新之间丢失。

例如,如果您想使用 localStorage:

<script type="text/javascript">
// properties
var count = 0;
var counter = null;

window.onload = function() {
initCounter();
};

function initCounter() {
// get count from localStorage, or set to initial value of 1000
count = getLocalStorage('count') || 1000;
counter = setInterval(timer, 1000); //1000 will run it every 1 second
}

function setLocalStorage(key, val) {
if (window.localStorage) {
window.localStorage.setItem(key, val);
}

return val;
}

function getLocalStorage(key) {
return window.localStorage ? window.localStorage.getItem(key) : '';
}

function timer() {
count = setLocalStorage('count', count - 1);
if (count == -1) {
clearInterval(counter);
return;
}

var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;

document.getElementById("timer").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left to complete this transaction"; // watch for spelling
}
</script>
<div id="timer"></div>

您可以在这里尝试一下:https://jsfiddle.net/rcg4mt9x/

关于javascript - 希望 javascript 倒计时即使在刷新后也能从原来的位置继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43134829/

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