Search code examples
javascriptjqueryuser-inputcountdown

javascript countdown with start/stop/reset and input time from user


I am basically want the page to take a user input of the time in seconds.

After that I want the countdown to start when the user presses "Start" button "Pause" when the pause button is pressed. Also a reset button so that the user can start the countdown from the beginning.

Here is what i got so far:

<script>
var CCOUNT;
            $(document).ready(function(){
            $('#btnct').click(function() {
            CCOUNT = $('#seconds').val();
            cdreset();
            });
var t, count;
function cddisplay() {
  document.getElementById('timespan').innerHTML = count;
};
function countdown() {
    // starts countdown
    cddisplay();
    if (count == 0) {
        // time is up
    } else {
        count--;
        t = setTimeout("countdown()", 1000);
    }
};
function cdpause() {
    // pauses countdown
    clearTimeout(t);
};
function cdreset() {
    // resets countdown
    cdpause();
    count = CCOUNT;
    cddisplay();
};
</script>
<body>
 <form id="frm"> 
  Seconds: 
  <input type="text" id="seconds" name="seconds" value="0" size="2" maxlength="2"/> 
  <br/>
  <input type="button" id="btnct" value="Input"/>
  </form>
<span id="timespan"></span>
<input type="button" value="Start" onclick="countdown()">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset()">
</body>`

But its not working, It worked when i left out the user input part and just initialized CCOUNT. But I want the page to take user input.


Solution

  • This works: http://jsfiddle.net/robschmuecker/XZXLk/

    Javascript with jQuery

    var CCOUNT;
    $(document).ready(function () {
        $('#btnct').click(function () {
            CCOUNT = $('#seconds').val();
            cdreset();
        });
    });
    var t, count;
    
    function cddisplay() {
        document.getElementById('timespan').innerHTML = count;
    }
    
    function countdown() {
        // starts countdown
        cddisplay();
        if (count === 0) {
            // time is up
        } else {
            count--;
            t = setTimeout(countdown, 1000);
        }
    }
    
    function cdpause() {
        // pauses countdown
        clearTimeout(t);
    }
    
    function cdreset() {
        // resets countdown
        cdpause();
        count = CCOUNT;
        cddisplay();
    }
    

    HTML:

    <form id="frm">Seconds:
        <input type="text" id="seconds" name="seconds" value="0" size="2" maxlength="2" />
        <br/>
        <input type="button" id="btnct" value="Input" />
    </form>
    <span id="timespan"></span>
    
    <input type="button" value="Start" onclick="countdown()">
    <input type="button" value="Stop" onclick="cdpause()">
    <input type="button" value="Reset" onclick="cdreset()">