javascript stopwatch – How to Create a Stopwatch in JavaScript?

javascript stopwatch build a stopwatch with HTML, CSS, and plain JavaScript Example with demo. How to create a simple stopwatch using JavaScript?

javascript stopwatch

There is a built-in function in JavaScript called Date.now(). Stopwatch in javascript. you start it with a call to start(). You can pause the stopwatch with a call to suspend(). Javascript Stopwatch demo with start, stop controls and lap counter.

HTML Code
Let’s start with simple HTML.

Pure JavaScript Code
Let’s start with simple JavaScript code.

var h2 = document.getElementsByTagName('h2')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    seconds = 0, minutes = 0, hours = 0,
    t;

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }
    
    h2.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

    startstopwatch();
}
function startstopwatch() {
    t = setTimeout(add, 1000);
}
startstopwatch();


/* stopwatch Start button */
start.onclick = startstopwatch;

/* stopwatch Stop button */
stop.onclick = function() {
    clearTimeout(t);
}

/* stopwatch Clear button */
clear.onclick = function() {
    h2.textContent = "00:00:00";
    seconds = 0; minutes = 0; hours = 0;
}

Don’t Miss : timer 1 hour

javascript count time

The getTime() method returns the number of milliseconds since midnight of January 1, 1970.

var st = new Date().getTime();

for (i = 0; i < 50000; ++i) {
// do something
}

var end = new Date().getTime();
var time = end - st;
alert('Execution time: ' + time);

Demo : Javascript Stopwatch

html timer









I hope you get an idea about javascript stopwatch.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment