javascript - 刷新时的持久性倒计时
问题描述
我有一个问题要解决,我不是 javascript 的大师,基本上当加载我的元素 id 时,它会在我的代码中从 2 小时分秒开始倒计时,但我有链接,点击刷新页面和正在刷新我的计数器我发现完整的计数器是链接: JavaScript 倒计时,添加小时和分钟
var count = 7200;
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 + " ora " + minutes + " minute" + seconds + " secunde ramase ";
}
我只是想让这个计数器在刷新时不重置。
解决方案
使用localStorage
:
var count = parseInt(localStorage.getItem("count")) || 7200;
function timer() {
//...
document.getElementById("timer").innerHTML = hours + " ora " + minutes + " minute" + seconds + " secunde ramase ";
localStorage.setItem("count", count);
}
要重定向您的页面并localStorage
在计时器命中时清除0
,请将此代码添加到您的函数中:
function timer() {
count = count - 1;
if (count == 0) {
localStorage.removeItem("count");
window.location.href = "home.html";
}
//...
}
推荐阅读
- cypress - 赛普拉斯测试之间通过状态的最佳实践是什么
- android - Android 的 Instant Run 与 Flutter 的 Hot Reload 和 React Native 的 Hot Reload 的区别?
- oracle - 如何以表格形式将单个值复制到所有字段?
- qliksense - 按 id 获取 Qlik 对象时未找到对象
- java - 在 Spring Data/hibernate 中获取实体的异常
- ld - 为什么递归 ld rpath 的应用程序不起作用?
- spring-boot - 嵌入 Vert.x 的 Spring Boot
- c - 在循环中使用 scanf() 扫描 CSV 文件在第一行和第二行开始之后停止
- python - 使用 Wand python 将 PDF 转换为图像
- opengl - 如何在带有 GPU 的 Google Compute Engine 上运行 Gazebo?