PDA

View Full Version : Javascript program



tcollins412
13 Dec 2010, 06:00 PM
I am writing a javascript program thatyou click the mouse on a button and it shows how many times you have pressed the button. here is the javascript for it

<script language="javascript">
var numcount=0;

function increasecounter(){

numcount++;

document.getElementById('countdiv').innerHTML=numcount;

}




</script>

and here is the html:

<div id='countdiv'>0</div><br/>
<input type=submit onclick="increasecounter();" value="Increment"></br>
<div id='time'></div><div id='score'></div><br/><input type='button' value='reset'>

now with that said, i would like to have a 30 second timer in the 'time' div. and when the timer goes off, i want the counter to stop counting the button clicks and show the score in the 'score' div. then when you click the 'reset' button the timer resets. how would i do this? if somebody could help me that would be GREATLY appreciated

gandalf117
16 Dec 2010, 03:05 PM
try this:


<head>
<script type='text/javascript'>

var numcount = 0;
var timing = 5000; //equals 5000 miliseconds or 5 seconds
var temp = setTimeout(displayCounter, timing);

function increasecounter(){

numcount++;
document.getElementById('countdiv').innerHTML = numcount;
}

function displayCounter(){

document.getElementById('score').innerHTML = numcount;
resetCounter();
}


function resetCounter(){

numcount = 0;
document.getElementById('countdiv').innerHTML = numcount;

if(temp)
clearTimeout(temp);
temp = setTimeout(displayCounter, timing);
}

</script>
</head>
<body>
<div id='countdiv'>0</div>
<input type="button" onclick="increasecounter();" value="Increment"></br>
<div id='time'></div><div id='score'></div><br/><input type='button' onclick="resetCounter();" value='reset'>
</body>

I made it 5 seconds to test it more quickly. I also changed the type of all the input fields to button, because if it is submit there is a risk that it may reload the page and all javascript starts again in that case.