javascript - Javascript计时器页面刷新
问题描述
我有一个计时器设置为从 10 分钟开始倒计时。我需要它,所以当用户刷新页面时它不会重置计时器。这是我的javascript。
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 10,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
解决方案
现在是 2019 年。我强烈建议使用 localStorage 或 sessionStorage 而不是 cookie。
const start = localStorage.getItem('startTime') || Date.now();
// ...rest of your code...
window.onload = function() {
localStorage.setItem('startTime', start);
// ...rest of your code...
};
在localStorage.setItem
设置. startTimer
_ start
取决于你想要的细节。
推荐阅读
- firebase - 无法使用我的 Firebase 会话设置带有谷歌存储的存储桶
- javascript - Webpack 热中间件不工作
- python - python 3.5 Flask 安装在 apache 2.4 上
- ios - UILabel 中的不同文本在 UICollectionView 单元格中保持相同的字体大小
- java - 如何将自定义插件发布到本地 Maven,然后在另一个本地项目中使用?
- html - 如何在图像上添加细节?
- android - 尝试使用 URLconnection 但我收到错误
- slurm - 来自 aprun 的 Slurm
- angular - 在 TypeScript.2.7 中找不到名称“TextDecoder”
- javascript - 意外的令牌 { 语法错误