...

View Full Version : Javascript timer countdown



sabastious
01-12-2007, 11:08 PM
Trying to write a javascript countdown script. Here's what I got:


function timer(position,count)
{
var newCount
if (position == 'start') {
document.getElementById("timer").innerHTML=count
newCount = count - 1
alert(newCount);
setTimeout("timer('go',newCount)",1000)
}

if (position == 'go') {
document.getElementById("timer").innerHTML=count
}
}
</script>
</head>

<body onload="timer('start',10);">

onload starts the timer at 10 and then my first step was to have to go down to 9. But I get this javascript error message:

Error: newCount is not defined

But I have it as an alert right before I call it and it alerts the variable just fine. Why would it say it isnt defined?

Live script: http://webwork.shasta.com/mmo/battle.asp

david_kw
01-13-2007, 12:40 AM
You were close. First newCount needs to be a global variable the way it is set up. Second, the 'go' state needs to decrement newCount and reset the timer.



<html>
<head>
<title>Test</title>
<script type="text/javascript">
var newCount;
function timer(position,count)
{
if (position == 'start') {
document.getElementById("timer").innerHTML=count
newCount = count - 1
setTimeout("timer('go',newCount)",1000)
}

if (position == 'go') {
document.getElementById("timer").innerHTML=count
newCount--;
setTimeout("timer('go',newCount)",1000)
}
}
</script>
</head>
<body onload="timer('start',10);">
<div id="timer" />
</body>
</html>


david_kw

gatw
07-02-2007, 02:29 PM
Can u teach me how to do it? I don't understand the setTimeout portions

Philip M
07-02-2007, 03:19 PM
Presumably the countdown should stop at 0 and not continue negative.

so:-

if (position == 'go') {
document.getElementById("timer").innerHTML=count;
newCount--;
if (newCount >= 0) {
setTimeout("timer('go',newCount)",1000);
}
}

gatw - The setTimeout() method is used to cause an action to repeat. Two arguments are required, the name of the function to call and the required delay in millseconds.

Example:

var count = 0;
function neverends() {
count ++;
alert ("This is ten-second message No: " + count );
window setTimeout ("neverends()", 10000);
}

neverends(); // call the function after it has been declared to start the timer.

Note that subsequent staements are not delayed - the delay only applies to the specific function called.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum