Search code examples
javascriptstopwatch

Issue with Javascript Stopwatch counter


I have this time counter in fiddle

http://jsfiddle.net/oukjfavu/718/#

How do I remove the "minutes" part of the counter in h1 because I only need the seconds and millisecond section?

function format(ms) {
  var d = new Date(ms + t[5]).toString()
    .replace(/.*([0-9][0-9]:[0-9][0-9]).*/, '$1');
  var x = String(ms % 1000);
  while (x.length < 3) x = '0' + x;
  d += '.' + x;
  h1.textContent = d
  return d;
}

when I remove the minute part of the counter:

.replace(/.*([0-9][0-9]:[0-9][0-9]).*/, '$1');

to this

.replace(/.*[0-9][0-9]).*/, '$1');

The second counter won't update.

Thank you very much


Solution

  • Here's a shorter version

    var startTime = Date.now();
    
    var interval = setInterval(function() {
        var elapsedTime = Date.now() - startTime;
        var time = (elapsedTime / 1000).toFixed(3).toString();
        time = time.replace('.', ':');
        document.getElementById("timer").innerHTML = time;
    }, 1);
    #timer {
      font-weight: bold;
      font-size: 35px;
    }
    <span id="timer"></span>