当我重新加载页面时,停止刷新计时器

时间:2016-12-10 10:18:51

标签: javascript

每次刷新页面时,计时器都会重置。我希望它从它停止的地方继续,直到达到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>

帮助表示赞赏。

1 个答案:

答案 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);
}

» Fiddle