Search code examples
javascriptstopwatch

Lost trying to create a stopwatch


I'm trying to self-taugh JavaScript and while doing some texts with a stopwatch I got lost into this problem. It's working but it's always starting on 95:34:47 instead of 00:00:00

This is what i tried so far.

    <script>
        /*Timer Stuff*/
        function pad(num, size) {
            var s = "0000" + num;
            return s.substr(s.length - size);
        } 
        function formatTime(time) {
            var h = m = s = ms = 0;
            var newTime = '';

            h = Math.floor( time / (60 * 60 * 1000) );
            time = time % (60 * 60 * 1000);
            m = Math.floor( time / (60 * 1000) );
            time = time % (60 * 1000);
            s = Math.floor( time / 1000 );
            ms = time % 1000;

            newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
            return newTime;
        } 

        function update() {
            var d = new Date();
            var n = d.getTime();
            document.getElementById("time").innerHTML = formatTime(n);
        }

        function start() {
            MyVar = setInterval(update, 1);
        }
    </script>
</head>
<body>
        <div>Time: <span id="time"></span></div>
        <input type="button" value="start" onclick="start();">
</body>

I understand that I need to subtract an specific amount of time to match the timer accurately, however I can't figure out how to do it.


Solution

  • You need to store a variable with the start time, and subtract from that. The 95 you're getting for the hours is actually much higher, just being cropped, being that you're calculating from the Unix epoch.

    I would just do it something like this:

        function update() {
            var d = new Date();
            var n = d - startTime;
            document.getElementById("time").innerHTML = formatTime(n);
        }
    
        function start() {
            startTime = new Date();
            MyVar = setInterval(update, 1);
        }
    

    Note that you don't even need to use d.getTime() when subtracting -- you can just subtract Date objects themselves.