我目前有一个页面从MySQL数据库获取信息,每隔5分钟由cron更新
我希望每隔五分钟刷新一次页面,同时向用户显示“下一次更新”的可见倒计时
下面是我目前正在使用的代码,但我不确定如何使其静态 - 就像用户刷新页面时它只是重新开始倒计时。
我很感激任何帮助,甚至只是知道从哪里开始。
由于
<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 >
答案 0 :(得分:0)
使用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/