...

View Full Version : Countdown Timer



Slate99
12-02-2009, 01:40 PM
Hi All,

I am trying to set up a countdown function that will be called on the click of a button.

Function is below



function countDown(sec, min) {

sec--;
if (sec == -01) {
sec = 59;
min = min - 1;
} else {
min = min;
}
if (sec<=9) { sec = "0" + sec; }
time = (min<=9 ? "0" + min : min) + " min and " + sec + " sec ";
if (document.getElementById) { theTime.innerHTML = time; }
SD=window.setTimeout("countDown();", 1000);
if (min == '00' && sec == '00') { sec = "00"; window.clearTimeout(SD); }
}

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}

addLoadEvent(function() {

});




However I get an error after one second. Script can be found here - http://www.jivalot.co.uk/m.php

Can anyone help?

Kind regards,

Slate

Philip M
12-02-2009, 02:16 PM
That could never have worked! Try this instead:


<html>
<head>

<script type = "text/javascript">

var timeInSecs;
var ticker;

function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); // to start counter display right away
}

function tick() {
var secs = timeInSecs;
if (secs>0) {
timeInSecs--;
}
else {
clearInterval(ticker); // stop counting at zero
//startTimer(5 * 60); // and start again if required
}

var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var result = ((mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = result;
}

</script>

</head>

<body>
<input type = "button" value = "Start the timer" onclick = "startTimer(5 * 60)"><br>
<span id="countdown" style="font-weight: bold;"></span>
</body>
</html>

The scrpt is called by startTimer(seconds), and here is set to 5 * 60 = 300 seconds = 5 minutes.

You could extend the timer to show hours as well simply by:-


var result = ((hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins
+ ":" + ( (secs < 10) ? "0" : "" ) + secs;
Quizmaster: What is the only prime number between 60 and 65?
Contestant: 50.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum