ayyelmayo77 ayyelmayo77 - 20 days ago 5
Javascript Question

Countdown using vanilla JavaScript

I have this web page with a

textarea
and 3
buttons
. The
textarea
receives a number. The first
button
starts the coutdown from the number to 0, with a delayed output (one number per second, so if N is 10 it'll take 10 seconds). The second
button
pauses the countdown, and the third
button
resumes it (without starting over). Pressing the first
button
at any time during the execution restarts the coutdown with whatever number is in the
textarea
. This is the code I have so far:

<!DOCTYPE html>
<html>
<body>
<h2>Insert a number:</h2>
<textarea id="input"></textarea>
<br/>
<button id="start" onclick="begin()">BEGIN</button>
<button id="pause" onclick="pause()">PAUSE</button>
<button id="resume" onclick="resume()">RESUME</button>
<h1 id="result"></h1>
<script>
var isCounting=true,
input=document.getElementById("input"),
countSec;
function begin() {
countSec=input.value;
if (isNaN(countSec)) alert("NaN");
count();
}
function pause() {
isCounting=false;
}
function resume() {
isCounting=true;
count();
}
function count() {
var i,
bck=countSec;
for (i=0; i<=bck; i++) {
document.getElementById("result").innerHTML=countSec;
countSec--;
}
}
</script>
</body>
</html>


Is there a way to stop the execution for 1 second after
countSec--
? I've been trying for 2 hours to do something with Date objects and setTimeout but I just can't figure out how to pause after every
for
iteration

Answer

Here is an option:

    <script>
        var input=document.getElementById("input"),
            countSec,
            timer = null;

        function begin() {
            countSec=input.value;
            if (isNaN(countSec)) alert("NaN");
            if( timer === null ) {
                timer = setTimeout( count, 1000 );
            }
        }

        function pause() {
            clearTimeout( timer );
            timer = null;
        }

        function resume() {
            if( timer === null ) {
                timer = setTimeout( count, 1000 );
            }
        }

        function count() {
            if( countSec > 0 ) {
                countSec--;
            }

            document.getElementById("result").innerHTML = countSec;

            if( countSec > 0 ) {
                timer = setTimeout( count, 1000 );
            }
        }
    </script>

As begin is called it sets a timer on count after 1 second.

When later count is invoked it decreases the counter, updates the html and schedules itself to be recalled after 1 second with setTimeout() (unless -of course- the counter reached zero)

The scheduled task is stored into timer so it can be canceled with clearTimeout() (see pause())

To resume the countdown just call count() again.

timer is set to null when the counter is not running and is checked before starting it to ensure only one counter is running.

Comments