每次刷新页面时,计时器都会重置。我希望它从它停止的地方继续,直到达到0。
处理计时器的我的JS:
var target_date = new Date().getTime() + (1000*3600*48); // set the countdown date
var days, hours, minutes, seconds; // variables for time units
var countdown = document.getElementById("tiles"); // get tag element
getCountdown();
setInterval(function () { getCountdown(); }, 1000);
function getCountdown(){
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = pad( parseInt(seconds_left / 86400) );
seconds_left = seconds_left % 86400;
hours = pad( parseInt(seconds_left / 3600) );
seconds_left = seconds_left % 3600;
minutes = pad( parseInt(seconds_left / 60) );
seconds = pad( parseInt( seconds_left % 60 ) );
// format countdown string + set tag value
countdown.innerHTML = "<span>" + days + "</span><span>" + hours + "</span><span>" + minutes + "</span><span>" + seconds + "</span>";
}
function pad(n) {
return (n < 10 ? '0' : '') + n;
}
<div id="tiles"></div>
帮助表示赞赏。
答案 0 :(得分:1)
localStorage
会为你效力吗?
var persisted = Number(localStorage.getItem('target_date')),
target_date;
if(persisted > 0){
target_date = persisted;
} else {
target_date = Date.now() + (1000 * 3600 * 48);
localStorage.setItem('target_date', target_date);
}