【发布时间】:2013-06-10 00:57:10
【问题描述】:
我目前有一个页面从 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 >
【问题讨论】:
-
您能否详细说明在这种情况下“静态”是什么意思?您希望它在用户明确按下 F5 后同时继续倒计时?
-
是的,我基本上想要它,以便它记住所有用户的时间,不确定是否可以使用 javascript 完成,但如果用户在 3 分 15 秒时按 F5,脚本会记住几点钟了。
-
你应该在服务器端真正做到这一点,而不是依赖客户端代码。如果 cron 在特定时间清理它,那么在页面渲染代码中计算到下一个实例的时间应该很容易。
标签: javascript static countdown repeat