Question

I have created a javascript timer that starts at 40 and counts down by one, but it wont stop at 0 and i want it to display a message(not an alert)/add an item to a database when it hits 0, and then restart at 40 seconds. If you could provide any help, thanks in advance :D

<html>
<head>
<script type="text/javascript">
var c=40;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c-1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
</script> 
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
</form>
<p>Click on the button above. It will count down from 40</p>
</body>
</html>
Was it helpful?

Solution

You want to use setInterval rather than setTimeout as this will fire the method periodically according to the delay you specify.

This will restart the timer when the count hits 0:

    function timedCount() {
        document.getElementById('txt').value = c;
        c = c - 1;
        if (c == 0)
            c = 40;
    }

    function doTimer() {
        if (!timer_is_on) {
            timer_is_on = true;
            t = setInterval(function () {
                timedCount();
            }, 1000);                
        }
    }

If you want to stop the timer when the count hits 0 use this:

    function timedCount() {
        document.getElementById('txt').value = c;
        c = c - 1;
        if (c == 0) {
            c = 40;
            clearInterval(t); // Stops the interval
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top