为什么我的倒计时代码,一旦时间达到零并刷新页面,首次重新加载(倒计时结束后)值不显示?他们只在第二次重装后显示?
我正在尝试让逻辑工作,重新加载后可以重新启动/重新启动倒计时,但仅在完成一段时间之后。我几乎拥有它,但我一直在努力弄清楚为什么需要2次重新加载来重新开始倒计时......
// Time Pass Checker - Check if time has passed in order to run countdown again
function timepasschecker() {
if ((Date.now() - deadline) > 3000 ) {
localStorage.removeItem('t1');
localStorage.setItem(time_now);
}
};
// Number Logic
function render() {
if (delay) {
clearTimeout(delay);
delay = null;
}
var diff = (deadline - Date.now()) / 1000;
document.getElementById('d').innerHTML = Math.floor(diff / 86400);
document.getElementById('h').innerHTML = Math.floor(diff / 3600);
document.getElementById('m').innerHTML = Math.floor((diff / 60) % 60);
document.getElementById('s').innerHTML = Math.floor(diff % 60);
if (diff<=0) {
document.getElementById('d').innerHTML = "0";
document.getElementById('h').innerHTML = "0";
document.getElementById('m').innerHTML = "0";
document.getElementById('s').innerHTML = "0";
//setTimeout(function(){ localStorage.removeItem('t1'); }, 15000);
}
delay = setTimeout(render,1000);
};
var deadline = localStorage.getItem('t1') ? parseInt(localStorage.getItem('t1')) : (Date.now() + 6000);
var delay = null;
timepasschecker();
localStorage.setItem('t1',deadline);
render();
答案 0 :(得分:2)
请检查这个小提琴。 https://jsfiddle.net/jefzobo7/
我发现了一些错误。
`2。一旦其值小于0,就不会在本地存储中清除事物,也不会清除超时。
// Time Pass Checker - Check if time has passed in order to run countdown again
var isIntialized=true;
function timepasschecker() {
if ((Date.now() - deadline) > 3000 ) {
localStorage.removeItem('t1');
localStorage.setItem('t1',(Date.now()+6000).toString());
}
};
// Number Logic
function render() {
if (delay) {
clearTimeout(delay);
delay = null;
}
var diff = (deadline - Date.now()) / 1000;
console.log("diff",diff);
document.getElementById('d').innerHTML = Math.floor(diff / 86400);
document.getElementById('h').innerHTML = Math.floor(diff / 3600);
document.getElementById('m').innerHTML = Math.floor((diff / 60) % 60);
document.getElementById('s').innerHTML = Math.floor(diff % 60);
if (diff<=0) {
document.getElementById('d').innerHTML = "0";
document.getElementById('h').innerHTML = "0";
document.getElementById('m').innerHTML = "0";
document.getElementById('s').innerHTML = "0";
//setTimeout(function(){ localStorage.removeItem('t1'); }, 15000);
localStorage.removeItem('t1');
}
delay = setTimeout(render,1000);
if(diff<=0){
clearTimeout(delay);
}
};
var deadline = localStorage.getItem('t1') ? parseInt(localStorage.getItem('t1')) : (Date.now() + 6000);
var delay = null;
timepasschecker();
localStorage.setItem('t1',deadline);
render();
希望这会有所帮助。如有问题请告诉我:))