[英]Static Repeating Countdown
我目前有一個頁面,該頁面從MySQL數據庫獲取聯合信息,該數據庫由cron每5分鍾更新一次
我想每五分鍾刷新一次頁面,但還要向用戶顯示“下一次更新”的可見倒計時
下面是我當前正在使用的代碼,但是我不確定如何使其靜態化-因為當用戶刷新頁面時,它只是重新開始倒計時。
我將不勝感激,即使只是知道從何開始。
謝謝
<script>
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
Timer.innerHTML = " Time's up ";
window.setTimeout("Tick", 1000);
CreateTimer("timer", 5)
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds);
Timer.innerHTML += " " + TotalSeconds;
Timer.innerHTML = TimeStr;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : +Time;
}
</script>
<div id="timer" >
<script type="text/javascript">window.onload = CreateTimer("timer", 5);</script>
</div >
使用beforeunload將當前狀態存儲在cookie中,然后從那里繼續執行表單。
這是一個示例(還有更優雅的計時器:-)
<html>
<head>
<title></title>
<script src="http://rawgithub.com/timseverien/cm.js/master/cm.js"></script>
</head>
<body>
<div id="time"></div>
<script type="text/javascript">
(function(){
var Timer = window.Timer = function(t, el, cookie){
this.cookie = cookie || false;
this.el = el;
this.t = this.cookie&&CM.get('t') || (t * 60 * 1000);
this.d = new Date(this.t);
this.event = new CustomEvent('onend');
this.show();
return this.el;
}
//https://gist.github.com/aemkei/1180489
Timer.prototype.pad = function(a,b){return([1e15]+a).slice(-b)};
Timer.prototype.format = function(){
return this.pad(this.d.getMinutes(), 2) + ':' + this.pad(this.d.getSeconds(), 2);
}
Timer.prototype.show = function(){
var self = this;
window.addEventListener('beforeunload', function(event) {
self.cookie&&CM.set('t', self.t);
}, false);
self.el.innerHTML = self.format();
setTimeout(function(){
self.t -= 1000;
self.d = new Date(self.t);
if(self.t > 0)
self.show();
else{
CM.clear();
self.el.innerHTML = self.format();
self.el.dispatchEvent(self.event);
}
}, 1000)
}
})();
var timer = new Timer(5, document.getElementById('time'), true);
timer.addEventListener('onend', function(e){
alert('timer is ended! (you can refresh here)');
//location.reload();
}, false)
</script>
</body>
</html>
這是現場示例(沒有cookie) http://jsfiddle.net/55p7f/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.