Forum Moderators: open
Does anyone have a better way?
Also if the begin button is clicked on more than once, the timer speeds up. Does anyone have a fix for that?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 strict//EN">
<HTML>
<HEAD>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<TITLE>Timer</TITLE>
<SCRIPT language=javascript>
var a
var b
a=10
b=0
function begin()
{
document.getElementById("number").value=a;
if(b==9)
{a=5; b=b+1; setTimeout("begin()", 1000);}
else if (b==14)
{a=60; b=b+1; setTimeout("begin()", 1000);}
else if (b==74)
{a=10; b=b+1; setTimeout("begin()", 1000);}
else if (b==85)
{alert("Time's up");}
else {a=a-1; b=b+1; setTimeout("begin()", 1000);}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<input type=button value="Begin" onClick= begin()>
<input type=text id= "number" value= "10">
</FORM>
</BODY>
</HTML>
Also if the begin button is clicked on more than once, the timer speeds up. Does anyone have a fix for that?
The reason for that is because each time you click, you start an additional setTimeout timer. What you need to do is check to see if the timer is already running before you call setTimeout again. You might consider splitting out the functionality that starts the timer from the functionality that increments the timer.
And I still think your progress bar is cool.
Thanks, one of the best 20 mins I ever spent, so many people have pinched that one!
ok, to the point, I think your code is a little clunky, lets see if we can jiggle it a bit.....
var timers = new Array( 10, 5, 60, 10);
var timer = 0;
var started = 0;function startTimer() {
// Quit if timers already started
if( started) return;
started = 1;count();
}function count() {
// Display on screen
var div = document.getElementById( "display");
div.innerHTML = timers[ timer];if(!timers[ timer]) { // This timer up?
// Put code here for between each timer
alert( "New time!");if( timer < timers.length) timer++; // Start next timer
else { // All timers run out?
timeUp();
return;
}
}timers[ timer]--; // 1 second
setTimeout( "count();", 1000);
}function timeUp() {
alert( "Time's up!");
}
ok, I've tested that, and it works ok. You'll have to change the display on screen bit to use the progress bar. Let us know if it needs tweaking.