'jQuery Stopwatch with milliseconds

I've found this usefull JS in jQuery for a stopwatch having hours, minutes and seconds. http://daokun.webs.com/jquery.stopwatch.js

Thing is, the hour counter is useless for me, I'd rather have a milliseconds counter showing up. I'm using this JS linked up to a button to start it:

$('.easy').click(function(){ 
$("#demo").stopwatch().stopwatch('start');});

Easy being the class for the button and Demo being the ID for the DIV

<div id="demo" >00:00:00</div>

What stops the counter is a if, else statement from a progress bar:

 else{
    $("#demo").stopwatch().stopwatch('stop');           
    }

The code for that else is actually longer and the counter stops once the bar hits 100, means that I covered up the rest from 0 to 99 with if and else if statements.

Anyway, how can that JS be edited to have a counter with minues, seconds and milliseconds? Or is there is any other jQuery plugin to have such counter?



Solution 1:[1]

You really don't event need to use the plugin, it's as simple as using setInterval() to make your own timer, which is exactly what the stopwatch plugin does.

jsFiddle

HTML

<div id="timer"><span class="value">0</span> ms</div>?

JS

setInterval(updateDisplay, 1); // every millisecond call updateDisplay

function updateDisplay() {
    var value = parseInt($('#timer').find('.value').text(), 10);
    value++;
    $('#timer').find('.value').text(value);
}?

Solution 2:[2]

If you'd looked through the code, you'd find the defaultFormatMilliseconds() function, which you could modify:

    return [pad2(hours), pad2(minutes), pad2(seconds), millis].join(':');
                                                     ^^^^^^^^---add milliseconds.

Solution 3:[3]

I tried modifying the codes so that it will allow us to see counting accurate up to the last millisecond, but that just made the stopwatch slower (as of now, I don't know if the slow down is browser/system hardware dependent).

Anyway, these codes will allow you to specify an update interval up to 100 (Hence giving you a stop watch accurate up to 0.0 seconds, without slowing down).

EDIT: I didn't include jinvtervals.js so that the stopwatch will use the default formatter.

Javascript:

function defaultFormatMilliseconds(x) {
    var millis, seconds, minutes, hours;
    millis = Math.floor((x % 1000) / 100);
    x /= 1000;
    seconds = Math.floor(x % 60);
    x /= 60;
    minutes = Math.floor(x % 60);
    x /= 60;
    hours = Math.floor(x % 24);
    // x /= 24;
    // days = Math.floor(x);
    return [pad2(hours), pad2(minutes), pad2(seconds)].join(':') + "." + millis;
}

HTML

<script type="text/javascript">

    $(function () {
        $('#swhTimeExposed').stopwatch({
            updateInterval: 100
        });

        $('#btnSearch').button({
            icons: {
                primary: "ui-icon-clock"
            },
            text: true
        })
            .bind('click', function (e) {
                // Start Stop watch
                $('#swhTimeExposed').stopwatch('start');
            }
        );
    });
</script>

<span id="swhTimeExposed"> 00:00:00.0 </span>
<button type="submit" id="btnSearch" >Start</button>

Solution 4:[4]

$(document).ready(function () {
    $(".resume,.restart").hide();
    $(".present_condition").hide().first().show();
    var timer;
    var h, m, s, c = 99;

    // Start Event
    $(".start").click(function () {
        $(".present_condition").not($(".present_condition").eq(3).show()).hide();
        $(".pause,.stop,.reset").attr('disabled', false);
        startRestartInterval();
    });

    // Stop Event
    $(".stop").click(function () {
        $(".present_condition").not($(".present_condition").eq(1).show()).hide();
        $(".pause,.stop").attr('disabled', true);
        $(".reset,.restart").attr('disabled', false);
        $(".start,.resume").hide();
        $(".restart").show();
        getValues();
        pauseAt = (`STOPPED AT: ${h} HH, ${m} MM, ${s} SS.`);
        $("#stopTimeStamp").html("<p>" + pauseAt + "</p>");
        clearInterval(timer);
    });

    // Restart Event
    $(".restart").click(function () {
        $(".present_condition").not($(".present_condition").eq(3).show()).hide();
        h = m = s = c = 0;
        startRestartInterval();
        $(".pause,.stop").attr('disabled', false);
        $(".start").attr('disabled', true);
        $(".start").show();
        $(".resume,.restart").hide();
    });

    // Pause Event
    $(".pause").click(function () {
        getValues();
        pauseAt = "PAUSE AT: " + h + " HH, " + m + " MM, " + s + " SS.";
        $(".pauseValue").css("color", "blue").text(pauseAt);
        $("#pauseTimeStamp").append("<p>" + pauseAt + "</p>");
        $(".present_condition").not($(".present_condition").eq(2).show()).hide();
        $(".start,.restart").hide();
        $(".resume").show();
        $(".pause").attr('disabled', true);
        $(".resume").attr('disabled', false);
        clearInterval(timer);
    });

    // Resume Event
    $(".resume").click(function () {
        getValues();
        startRestartInterval();
        $(".start").show();
        $(".resume,.restart").hide();
        $(".pause,.stop").attr('disabled', false);
        $(".start").attr('disabled', true);
        $(".present_condition").not($(".present_condition").eq(3).show()).hide();
    });

    // Reset Event
    $(".reset").click(function () {
        clearInterval(timer);
        $("#pauseTimeStamp,#stopTimeStamp").empty();
        $("th").text("00");
        $(".start").show();
        $(".resume,.restart").hide();
        $(".pause,.stop,.reset").attr('disabled', true);
        $(".start").attr('disabled', false);
        $(".present_condition").hide().first().show();
    });

    // Functions
    function startRestartInterval() {
        timer = setInterval(function () {
            if (c < 99) {
                c++;
            }
            else {
                c = 0;
                if (s < 59) {
                    s++;
                } else {
                    s = 0;
                    if (m < 59) {
                        m++;
                    } else {
                        m = 0;
                        if (h < 59) {
                            h++;
                        }
                    }
                }
            }
            $("th").eq(0).text((h < 10) ? ("0" + h) : h);
            $("th").eq(1).text((m < 10) ? ("0" + m) : m);
            $("th").eq(2).text((s < 10) ? ("0" + s) : s);
            $("th").eq(3).text((c < 10) ? ("0" + c) : c);
        }, 10);
    }
    function getValues() {
        h = parseInt($("#hr").text());
        m = parseInt($("#min").text());
        s = parseInt($("#sec").text());
        c = parseInt($("#cSec").text());
    }
});
.btn {
  margin-top: 10px;
}
.green {
  color: #b58b00;
}
.blue {
  color: #005ce6;
}
.red {
  color: red;
}
.dark {
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
    <div class="heading">
        <h1>STOPWATCH</h1>
    </div>
    <div class="timeBar">
        <table>
            <tr>
                <th class="time_slot" id="hr">00</th>
                <th class="time_slot" id="min">00</th>
                <th class="time_slot" id="sec">00</th>
                <th class="time_slot" id="cSec">00</th>
            </tr>
            <tr>
                <td class="heading_slot">Hours</td>
                <td class="heading_slot">Minutes</td>
                <td class="heading_slot">Seconds</td>
                <td class="heading_slot">C-Seconds</td>
            </tr>
        </table>
    </div>
    <div class="buttonBar">
        <button type="button" disabled class="btn restart green">Restart</button>
        <button type="button" class="btn start green">Start</button>
        <button type="button" disabled class="btn resume green">Resume</button>
        <button type="button" disabled class="btn pause blue">Pause</button>
        <button type="button" disabled class="btn stop red">Stop</button>
        <button type="button" disabled class="btn reset dark">Reset</button>
    </div>
    <div class="messageBar">
        <h4 class="dark present_condition">ENTER TIME & HIT START..!</h4>
        <h4 class="red present_condition">STOPPED</h4>
        <h4 class="present_condition"><span class="pauseValue"></span></h4>
        <h4 class="green present_condition">RUNNING...</h4>
    </div>
    <div class="blue history" id="pauseTimeStamp"></div>
    <div class="red history" id="stopTimeStamp"></div>
</body>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Marc B
Solution 3
Solution 4 Mihir Sangani