Hallo,
hab gerade ein kleines Skript geschrieben, mit dem man einen oder mehrere Timer gleichzeitig laufen lassen kann. Benötigt wird initial im Element "javascript-timer-init" die aktuelle Zeit (time()), in den durchgehend nummerierten Elementen "javascript-timer-#" die Zeit, auf das der Timer zählen soll (also den Unix-Timestamp des Ereignisses).
Die Countdown-Zeit ergibt dann javascript-timer-# minus javascript-timer-init. Somit kann zusätzlich zum Countdown, der logischerweise sekündlich aktualisiert wird auch die tatsächliche Zielzeit angezeigt werden (momentan noch nicht eingebaut).
Die Ausgabe ist frei über display() steuerbar, momentan auch nur in Sekunden.
Vielleicht hilft es ja dem ein oder anderen als Inspiration.
Code:
<html>
<head>
<script type="text/javascript">
// singleton timer
var Timer = new function()
{
// store all instances here
this.instances = [];
// init with id, current init time and destination time
// init time needed to synchronize clock (server-side/client-side)
this.init = function(id, initTime, destTime)
{
this.instances[id] = {
"iv" : setTimeout("Timer.countdown('" + id + "')", 1000), // set interval did not work properly
"rest" : destTime - initTime}; // we are just counting down
}
this.countdown = function(id)
{
if (this.instances[id].rest > 0) {
setTimeout("Timer.countdown('" + id + "')", 1000); // new timeout
}
this.display(id, this.instances[id].rest); // call display function
--this.instances[id].rest; // decrement
}
this.display = function(id, seconds)
{
// display what ever you like
document.getElementById(id).innerHTML = seconds;
}
}
function init()
{
// look after timer init (needed for time synchronisation)
if (typeof document.getElementById("javascript-timer-init") != "undefined") {
var initTime = document.getElementById("javascript-timer-init").innerHTML;
var i = 1, e;
// increment "i" index, if not found, stop loop
while (document.getElementById("javascript-timer-" + i)) {
e = document.getElementById("javascript-timer-" + i);
var destTime = e.innerHTML;
// init timer with id, init time and destination time
Timer.init("javascript-timer-" + i, initTime, destTime);
++i;
}
}
}
// TODO use a better onload event
window.onload = init;
</script>
</head>
<body>
<div id="javascript-timer-init" style="display:none"><?=time()?></div>
<table border="1">
<tr>
<td>Eintrag 1</td>
<td id="javascript-timer-1"><?=strtotime("tomorrow")?></td>
</tr>
<tr>
<td>Eintrag 2</td>
<td id="javascript-timer-2"><?=(time() + 4)?></td>
</tr>
</table>
</body>
</html>
Vielleicht kann es ja der ein oder andere gebrauchen.