Click here to Skip to main content
15,905,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Wondering if someone can help me out. I am doing a countdown clock with control buttons. I can get the start button working and the clear button working, but have no idea how to do a pause/resume button. I tried finding some tuts online but do not know how to incorporate any of them into my code. If anyone can help it would be appreciated. Here is the code I have so far:

HTML
<html>
<head>
<title>Countdown clock</title>

<script type = "text/javascript" >
var running = false
var endTime = null
var timerID = null
function startTimer() {
    running = true
    now = new Date()
    now = now.getTime()

    endTime = now + (1000 * 30 * 1)
    showCountDown()
}

function showCountDown() {
    var now = new Date()
    now = now.getTime()
    if (endTime - now <= 0) {
        stopTimer()

alert("Time is up. Get back to work!.")
    } else {
        var delta = new Date(endTime - now)
        var theMin = delta.getMinutes()
        var theSec = delta.getSeconds()
        var theTime = theMin
        theTime += ((theSec < 10) ? ":0" : ":") + theSec
        document.forms[0].timerDisplay.value = theTime
        if (running) {
            timerID = setTimeout("showCountDown()",1000)
        }
    }
}
function stopTimer() {
    clearTimeout(timerID)
    running = false
    document.forms[0].timerDisplay.value = "0:00"
}
</script>

</head>

<body>

<FORM>
<INPUT TYPE="button" NAME="startTime" VALUE="Start 30 sec. Timer"
 >
<INPUT TYPE="button" NAME="clearTime" VALUE="Clear Timer"
 ><p>
<INPUT TYPE="text" NAME="timerDisplay" VALUE="0:30">
</FORM>

</body>
</html>
Posted
Updated 27-Oct-15 11:15am
v2
Comments
Wombaticus 27-Oct-15 18:13pm    
You seem to have missed out the onclick event on your buttons... but that aside, you can easily pause and resume the display by adding two buttons
<INPUT TYPE="button" NAME="pauseTime" VALUE="Pause Timer" />
<INPUT TYPE="button" NAME="resumeTime" VALUE="Resume Timer" />
and two corresponding functions
function pauseTimer() {
clearTimeout(timerID);
running = false;
}
function resumeTimer() {
running = true;
timerID = setTimeout("showCountDown()",1000);
}
However... this just pauses the display, time itself does not stop, so on resuming it carries on as if the clock had been counting down all the while. If you want to carry on with the next number down you should use a counter to count down, not the real time.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900