Count Down

WarriorH

New Member
Messages
55
Reaction score
0
Points
0
Hi guys, I need a VERY simple count down. I need something to count down 20 minutes, then loop. I need this as a way to show users how much longer they have until database clears.
 

marshian

New Member
Messages
526
Reaction score
9
Points
0
Add this to your <head>:
HTML:
<script type="text/javascript">
	//How much time there is on the timer when the page has loaded? (in seconds)
	var timeleft = 20*60
	//How much time does the timer have to reset to? (in seconds)
	var resettime = 20*60;
	function countdown() {
		setTimeout(countdown, 1000);
		if(timeleft > 0) {
			timeleft--;
		} else {
			timeleft = resettime;
		}
		document.getElementById("time").innerText = ((timeleft-timeleft%60)/60)+":";
		if(timeleft%60 < 10) document.getElementById("time").innerText += "0";
		document.getElementById("time").innerText += ""+timeleft%60;
		document.getElementById("time").textContent = document.getElementById("time").innerText;
	}
	function startTimer() {
		timeleft++;
		countdown();
	}
</script>

add onload="startTimer()" to your <body> tag
eg
HTML:
<body onload="startTimer()">
and then use a <span> with id "time" where you want to put your timer.
eg
HTML:
<span id="time"></span>

Tested in IE and FF (omfg, WILL YOU FINALLY WORK?!)

Marshian
 
Last edited:

woiwky

New Member
Messages
390
Reaction score
0
Points
0
That code looks alright for the most part. The only thing is that the OP said that after 20 minutes, the db is cleared. This sounds to me like a cron job rather than something that would rely on the clients. In this case it would be a good idea to have php store the timestamp of the last clearing in the db(in a table that isn't cleared, of course), then have that timestamp loaded into the JS so it can count down from the approximate time remaining. That's basically just changing

var timeleft = 20*60;

to

var timeleft = <?php print (($t = $lastclear + 1200 - time()) > 1200 ? 1200 : $t);?>;

where $lastclear is the time of the last clearing retrieved from the db.
 

marshian

New Member
Messages
526
Reaction score
9
Points
0
Yes, I realised this, but he said very simple, so I supposed he just wanted an estimation.
 
Top