Hi Everyone, Google has failed me in my search for a really simple coundown script - the ones offered are all rather complicated. I simply need a timer which counts down in Hours, minutes and seconds (rather than to a specific date). The hour/minute/second value would be passed to the JS by a PHP script once per page load, I just need the numbers to descend at the right rate! Any help would be much appreciated, my JS knowledge is nil!
If you could convert the time into a timestamp it would be quite simple. You would just create a function like: function countDown() { //theTime is gotten from your php script and it should be a timestamp. //minus 1 second theTime -= 1; //do some math var date = new Date(theTime*1000); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); //new time var newTime = hours + ':' + minutes + ':' + seconds; //output data to a div called counter document.getElementById('counter').innerHTML = newTime; //loop t = setTimeout(countDown(),1000); } countDown() Code (markup):
Hi Thanks a lot for your suggestion; I gave it a try but unfortunately it doesn't seem inclined to display anything - probably because of the way that I have set it up. Here's a sample of what the PHP generates, can you see any obvious problem? <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>foobar</title> <link rel="stylesheet" href="wq-question-styles.css" type="text/css" /> <script type="text/javascript"> function countDown() { //theTime is gotten from your php script and it should be a timestamp. //minus 1 second theTime -= 1279885216; //do some math var date = new Date(theTime*1000); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); //new time var newTime = hours + ':' + minutes + ':' + seconds; //output data to a div called counter document.getElementById('time').innerHTML = newTime; //loop t = setTimeout(countDown(),1000); } countDown() </script> </head> <body> <div id="time"></div><!--Stays Blank - No Time Appears--> HTML:
This line: t = setTimeout(countDown(),1000); Should be like this t = setTimeout('countDown()',1000); theTime -= 1279885216; //Why did you minus that large number? It should be whatevers equal to one second in your timestamp And since you are putting that in your head tag you can only access the div once it has been created. Instead of: document.getElementById('time').innerHTML = newTime; Try: if(document.getElementById('time')) //checks to see if element exists { document.getElementById('time').innerHTML = newTime; } A few debuging options would be putting a temp alert('ping'); inside your countDown() function to see if it is looping every second. You could also check to see if your php gave javascript the right time by using alert(theTime) Also theTime should only be gotten once at the beginning of the script.