Skip to content

Instantly share code, notes, and snippets.

@electricg
Last active March 27, 2024 20:59
Show Gist options
  • Star 53 You must be signed in to star a gist
  • Fork 21 You must be signed in to fork a gist
  • Save electricg/4372563 to your computer and use it in GitHub Desktop.
Save electricg/4372563 to your computer and use it in GitHub Desktop.
Stopwatch in javascript
Copyright (c) 2010-2015 Giulia Alfonsi <electric.g@gmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stopwatch</title>
</head>
<body onload="show();">
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
<input type="button" value="stop" onclick="stop();">
<input type="button" value="reset" onclick="reset()">
</body>
</html>
// Simple example of using private variables
//
// To start the stopwatch:
// obj.start();
//
// To get the duration in milliseconds without pausing / resuming:
// var x = obj.time();
//
// To pause the stopwatch:
// var x = obj.stop(); // Result is duration in milliseconds
//
// To resume a paused stopwatch
// var x = obj.start(); // Result is duration in milliseconds
//
// To reset a paused stopwatch
// obj.stop();
//
var clsStopwatch = function() {
// Private vars
var startAt = 0; // Time of last start / resume. (0 if not running)
var lapTime = 0; // Time on the clock when last stopped in milliseconds
var now = function() {
return (new Date()).getTime();
};
// Public methods
// Start or resume
this.start = function() {
startAt = startAt ? startAt : now();
};
// Stop or pause
this.stop = function() {
// If running, update elapsed time otherwise keep it
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0; // Paused
};
// Reset
this.reset = function() {
lapTime = startAt = 0;
};
// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
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 show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
clearInterval(clocktimer);
}
function reset() {
stop();
x.reset();
update();
}
@electricg
Copy link
Author

@deanpanayotov
Copy link

Very nice! Thank you! I used it here: http://codepen.io/d_panayotov/pen/jwJGF with slight modifications.

@denisstoyanov
Copy link

Thank you :)

@michaelWagner
Copy link

Well done, thanks!

@psulek
Copy link

psulek commented Oct 7, 2014

Each of JS stopwatch i found does not survive when client operating system has changed its system time, for example to back in time. I'm looking for JS stopwatch wich will survive system(local) time changes..

@dnsilva
Copy link

dnsilva commented Jul 2, 2015

Simple and functional, nice job. Thanks!

@electricg
Copy link
Author

Added license as per request.

@TameshwarNirmalkar
Copy link

very simple and nice

@tchain2
Copy link

tchain2 commented Jan 2, 2016

Thanks !

The core code worked in part on my windows box. However, sometimes the buttons to stop/reset take several clicks to function (on firefox).

Thinking that updating the screen every msec might be a little too much overhead, I got them to work if the interval is changed from 1 msec to 1000 msec. I.e. clocktimer = setInterval("update()", 1000);

Then of course the formatTime function needs to be adjusted.

@rstormsf
Copy link

I would change https://gist.github.com/electricg/4372563#file-stopwatch-js-L61

    var h = m = s = ms = 0;

to

    var h, m, s, ms = 0;

@NormanBenbrahim
Copy link

@rstomsf but that leaves all variables except ms to be of type undefined, which makes them ambiguous. At least setting them all to 0 gives them all the number type.

@heriipurnama
Copy link

Nice

@asdcoder
Copy link

The html doesnt work for me

@lacostenycoder
Copy link

Sweet!

@pisaiah
Copy link

pisaiah commented Jan 29, 2017

<script> var _0x1d90=["\x3C\x62\x6F\x64\x79\x20\x6F\x6E\x6C\x6F\x61\x64\x3D\x22\x73\x68\x6F\x77\x28\x29\x3B\x22\x3E\x3C\x73\x70\x61\x6E\x20\x69\x64\x3D\x22\x74\x69\x6D\x65\x22\x3E\x3C\x2F\x73\x70\x61\x6E\x3E\x5B\x3C\x73\x70\x61\x6E\x20\x6F\x6E\x63\x6C\x69\x63\x6B\x3D\x22\x73\x74\x61\x72\x74\x28\x29\x22\x3E\x53\x54\x41\x52\x54\x7C\x3C\x2F\x73\x70\x61\x6E\x3E\x3C\x73\x70\x61\x6E\x20\x6F\x6E\x63\x6C\x69\x63\x6B\x3D\x22\x73\x74\x6F\x70\x28\x29\x22\x3E\x50\x41\x55\x53\x45\x7C\x3C\x2F\x73\x70\x61\x6E\x3E\x3C\x73\x70\x61\x6E\x20\x6F\x6E\x63\x6C\x69\x63\x6B\x3D\x22\x72\x65\x73\x65\x74\x28\x29\x22\x3E\x53\x54\x4F\x50\x5D\x3C\x2F\x73\x70\x61\x6E\x3E\x3C\x2F\x62\x6F\x64\x79\x3E","\x77\x72\x69\x74\x65","\x67\x65\x74\x54\x69\x6D\x65","\x73\x74\x61\x72\x74","\x73\x74\x6F\x70","\x72\x65\x73\x65\x74","\x74\x69\x6D\x65","\x30\x30\x30\x30","\x6C\x65\x6E\x67\x74\x68","\x73\x75\x62\x73\x74\x72","","\x66\x6C\x6F\x6F\x72","\x3A","\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64","\x69\x6E\x6E\x65\x72\x48\x54\x4D\x4C","\x75\x70\x64\x61\x74\x65\x28\x29"];document[_0x1d90[1]](_0x1d90[0]);var clsStopwatch=function(){var _0xf031x2=0;var _0xf031x3=0;var _0xf031x4=function(){return ( new Date())[_0x1d90[2]]()};this[_0x1d90[3]]= function(){_0xf031x2= _0xf031x2?_0xf031x2:_0xf031x4()};this[_0x1d90[4]]= function(){_0xf031x3= _0xf031x2?_0xf031x3+ _0xf031x4()- _0xf031x2:_0xf031x3;_0xf031x2= 0};this[_0x1d90[5]]= function(){_0xf031x3= _0xf031x2= 0};this[_0x1d90[6]]= function(){return _0xf031x3+ (_0xf031x2?_0xf031x4()- _0xf031x2:0)}};var x= new clsStopwatch();var $time;var clocktimer;function pad(_0xf031x9,_0xf031xa){var _0xf031xb=_0x1d90[7]+ _0xf031x9;return _0xf031xb[_0x1d90[9]](_0xf031xb[_0x1d90[8]]- _0xf031xa)}function formatTime(_0xf031xd){var _0xf031xe=m= s= ms= 0;var _0xf031xf=_0x1d90[10];_0xf031xe= Math[_0x1d90[11]](_0xf031xd/ (60* 60* 1000));_0xf031xd= _0xf031xd% (60* 60* 1000);m= Math[_0x1d90[11]](_0xf031xd/ (60* 1000));_0xf031xd= _0xf031xd% (60* 1000);s= Math[_0x1d90[11]](_0xf031xd/ 1000);ms= _0xf031xd% 1000;_0xf031xf= pad(m,2)+ _0x1d90[12]+ pad(s,2);if(pad(s,2)> 58&& pad(m,2)> 58){x[_0x1d90[5]]();x[_0x1d90[3]]();return _0xf031xf}else {return _0xf031xf}}function show(){$time= document[_0x1d90[13]](_0x1d90[6]);update()}function update(){$time[_0x1d90[14]]= formatTime(x[_0x1d90[6]]())}function start(){clocktimer= setInterval(_0x1d90[15],1);x[_0x1d90[3]]()}function stop(){x[_0x1d90[4]]();clearInterval(clocktimer)}function reset(){stop();x[_0x1d90[5]]();update()} </script>

@andytwoods
Copy link

I forked and updated to encapsulate everything https://gist.github.com/andytwoods/46eba3ddb06f78fb20bbf648def0e7d8
Thanks for original :)

@adamdickinson
Copy link

Super simple, but what about cycles? There are a heap of unnecessary and wasted DOM updates going on. Consider switching setInterval to requestAnimationFrame - that should make it a heap more performant. :)

@poa00
Copy link

poa00 commented Mar 27, 2024

I would change https://gist.github.com/electricg/4372563#file-stopwatch-js-L61

var h = m = s = ms = 0;

to

var h, m, s, ms = 0;

@rstormsf but that leaves all variables except ms to be of type undefined, which makes them ambiguous. At least setting them all to 0 gives them all the number type.

@NormanBenbrahim After reading the comments, I'm curious whether one way or the other is the (more) correct way to go about writing this... sweet gist though!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment