Matthew
Matthew

Reputation: 2246

Having trouble with Javascript Stopwatch

I'm working on a stopwatch, and this is my code for it. It makes perfect sense for me, but doesn't want to update for some reason.

HTML:

        <ul>

            <li id="hour">0</li>
            <li>:</li>
            <li id="min">0</li>
            <li>:</li>
            <li id="sec">0</li>

        </ul>

JS:

    var sec = document.getElementById("sec").value,
        min = document.getElementById("min").value,
        hour = document.getElementById("hour").value;

        function stopWatch(){
            sec++;
            if(sec > 59) {
            sec = 0;
            min++;
            } else if(min > 59){
            min = 0;
            hour++;
            }

            window.setTimeout("stopWatch()", 1000);

        }

        stopWatch();

Upvotes: 2

Views: 1741

Answers (6)

O.T.
O.T.

Reputation: 36

This is my complete code, this may help you out:

<html>
<head>
    <title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>
    <script language="JavaScript" type="text/javascript">
            var theResult = "";
            window.onload=function() {  document.getElementById('morefeature').style.display = 'none'; }
            function stopwatch(text) {
               var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var ms = d.getMilliseconds();
               document.stopwatchclock.stpwtch.value = + h + " : " + m + " : " + s + " : " + ms;
                if (text == "Start") {
                    document.stopwatchclock.theButton.value = "Stop";
                    document.stopwatchclock.theButton.title = "The 'STOP' button will save the current stopwatch time in the stopwatch history, halt the stopwatch, and export the history as JSON object. A stopped stpwatch cannot be started again.";
                    document.getElementById('morefeature').style.display = 'block';
                }
                if (text == "Stop") {
                  var jsnResult = arrAdd();
                  var cnt = 0; var op= 'jeson output';
                  for (var i = 0; i < jsnResult.length; i++) {
                      if (arr[i] !== undefined) {
                          ++cnt; /*json process*/
                          var j={ Record : cnt, Time : arr[i]};
                          var dq='"';
                          var json="{";
                          var last=Object.keys(j).length;
                          var count=0;
                          for(x in j){ json += dq+x+dq+":"+dq+j[x]+dq;  count++;
                          if(count<last)json +=",";
                          }
                          json+="}<br>";
                          document.write(json);
                      }
                  }
              }
              if (document.stopwatchclock.theButton.value == "Start") { return true;  }
              SD=window.setTimeout("stopwatch();", 100);
              theResult = document.stopwatchclock.stpwtch.value;
              document.stopwatchclock.stpwtch.title = "Start with current time with the format (hours:mins:secs.milliseconds)" ;
            }
            function resetIt() {
                if (document.stopwatchclock.theButton.value == "Stop") { document.stopwatchclock.theButton.value = "Start"; }
                window.clearTimeout(SD);
             }
            function saveIt() {
                var value = parseInt(document.getElementById('number').value, 10);
                value = isNaN(value) ? 0 : value; value++;
                document.getElementById('number').value =  value;
                var resultTitle = '';
                if(value == '1'){ resultTitle = "<h3>History</h3><hr color='black'>"; }
                var objTo = document.getElementById('stopwatchresult')
                var spanTag = document.createElement("span");
                    spanTag.id = "span"+value;
                    spanTag.className ="stopWatchClass";
                    spanTag.title ="The stopwatch showing current stopwatch time and a history of saved times. Each saved time are shown as total duration  (split time - stopwatch start time) and a lap duration (split time -  previous split time). And durations are shown in this format: 'hours:mins:secs.milliseconds'";
                    spanTag.innerHTML = resultTitle +"<br/><b>Record " + value+" =</b> " + theResult + "";
                    objTo.appendChild(spanTag);
               arrAdd(theResult);
                 return;
            }
            var arr = Array();
            function arrAdd(value){ arr.push(value); return arr;}
    </script>
    <style>
        center {
            width: 50%;
            margin-left: 25%;
        }

        .mainblock {
            background-color: #07c1cc;
        }

        .stopWatchClass {
            background-color: #07c1cc;
            display: block;
        }

        #stopwatchclock input {
            margin-bottom: 10px;
            width: 120px;
        }
    </style>
</head>
<body>
    <center>
        <div class="mainblock">
            <h1><b title="Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )">Stopwatch Application</b></h1>
            <form name="stopwatchclock" id="stopwatchclock">
                <input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
                <input type="button" name="theButton" id="start" onClick="stopwatch(this.value);" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." /><br />
                <div id="morefeature">
                    <input type="button" value="Reset" id="resetme" onClick="resetIt();reset();" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />
                    <input type="button" name="saver" id="split" value="SPLIT" onClick="saveIt();" title="The 'SPLIT' button will save the current stopwatch time in the stopwatch history. The stopwatch will continue to progress after split." />
                    <div>
                        <input type="hidden" name="number" id="number" value="0" />
            </form>
        </div>
        <div id="stopwatchresult"></div>
    </center>
</body>

Upvotes: 0

chepe263
chepe263

Reputation: 2812

Li elements has no value propertie, use innerHTML. You could store the values for sec, min & hour in variables. It is a nice idea to store the setTimeout() call to a variable in case you want to stop the clock later. Like "pause".

http://jsfiddle.net/chepe263/A3a9m/4/

<html>
    <head>
        <style type="text/css">
        ul li{
        float: left;
        list-style-type: none !important;

        }
        </style>
        <script type="text/javascript">//<![CDATA[ 
        window.onload=function(){

        var sec = min = hour = 0;
        var clock = 0;
        stopWatch = function(){
            clearTimeout(clock);
            sec++;
            if (sec >=59){
                sec = 0;
                min++;
            }
            if (min>=59){
                min=0;
                hour++;
            }
            document.getElementById("sec").innerHTML = (sec < 10) ? "0" + sec : sec;
            document.getElementById("min").innerHTML = (min < 10) ? "0" + min : min;
            document.getElementById("hour").innerHTML = (hour < 10) ? "0" + hour : hour;
            clock = setTimeout("stopWatch()",1000); }
        stopWatch();
        pause = function(){
        clearTimeout(clock);
            return false;
        }

        play = function(){
            stopWatch();
        return false;
        }

        reset = function(){
            sec = min = hour = 0;
            stopWatch();
        return false;
        }           

        }//]]>  
        </script>
    </head>
    <body>
        <ul>
            <li id="hour">00</li>
            <li>:</li>
            <li id="min">00</li>
            <li>:</li>
            <li id="sec">49</li>
        </ul>
    <hr />
    <a href="#" id="pause" onClick="pause()">Pause</a>
    <a href="#" id="Play" onClick="play()">Continue</a>
    <a href="#" id="Reset" onClick="reset()">Reset</a>
    </body>
</html>

Upvotes: 1

Stefan
Stefan

Reputation: 3041

    (function() {

        var sec = document.getElementById("sec").value,
        min = document.getElementById("min").value,
        hour = document.getElementById("hour").value;



        function stopWatch(){
            sec++;
            if(sec > 59) {
                sec = 0;
                min++;
            } else if(min > 59){
                min = 0;
                hour++;
            }
            document.getElementById("sec").textContent = sec
            document.getElementById("min").textContent = min
            document.getElementById("hour").textContent = hour
            window.setTimeout(stopWatch, 1000);
        }

        stopWatch();
    })();

Upvotes: 1

Brian
Brian

Reputation: 7654

The invocation should only be

window.setInterval(stopWatch, 1000);

So to use the stopwatch, put the function inside:

var sec = 0, min = 0, hour = 0;
window.setInterval(function () {
    "use strict";
    sec++;
    if (sec > 59) {
        sec = 0;
        min++;
    } else if (min > 59) {
        min = 0;
        hour++;
    }
    document.getElementById("sec").innerHTML = sec;
    document.getElementById("min").innerHTML = hour;
    document.getElementById("hour").innerHTML = hour;
}, 1000);

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

1) List items LI don't have values, they have innerHTML.

var sec = document.getElementById("sec").innerHTML; (not .value)

2) Nowhere in your code do you set the contents of your LIs. JavaScript doesn't magically associate IDs with variables - you have to do that bit yourself.

Such as:

document.getElementById("hour").innerHTML = hour;

3) Never pass a timeout as a string. Use an anonymous function:

 window.setTimeout(function() {stopWatch()}, 1000);

or, plainly:

 window.setTimeout(stopWatch, 1000);

Upvotes: 2

Bergi
Bergi

Reputation: 664307

A list item has no .value property. Inputs or textareas have. It should be

var sec = parseInt(document.getElementById("sec").innerHTML, 10),
    min = parseInt(document.getElementById("min").innerHTML, 10),
    hour = parseInt(document.getElementById("hour").innerHTML, 10);

which is also parsing them into numbers.

Also, don't pass a string to setTimeout. Pass the function you want to be called:

window.setTimeout(stopWatch, 1000);

And nowhere in your code you are outputting the updated variables. They are no magic pointers to the DOM properties, but just hold numbers (or strings in your original script).

Last but not least there's a logic error in your code. You are checking whether the minutes exceed 59 only when the seconds didn't. Remove that else before the if.

Upvotes: 2

Related Questions