0

I am trying to create a timer and increase it's value every ms.

My code currently looks like this, and isn't working (obviously) as it is concatenating the string. Is there any relatively straight forward way to implement this?

var num = '00:00:00';

setInterval(function(){
   num += '00:00:01'
}, 1);
  • 2
    Possible duplicate of [JavaScript seconds to time string with format hh:mm:ss](http://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss) – ppasler Jan 11 '17 at 16:43
  • @ppasler yes, i saw this one, but how can you increase every second without concatenating the string? –  Jan 11 '17 at 16:46
  • You really want to update every millisecond? `setInterval(..., 1)` – ppasler Jan 11 '17 at 16:50
  • @ppasler i think I'm going to have to increase that... machine keeps crashing –  Jan 11 '17 at 16:54
  • Every second should be enough, as you only show seconds. – ppasler Jan 11 '17 at 16:55
  • @ppasler no i wanted to show ms -- see question title –  Jan 11 '17 at 17:01

2 Answers2

2

Using += with a string adds a value to the end of a string. It's best to work with numbers. Set separate variables for the number of seconds, minutes and hours. If the number of one of them is in single digits, add a zero in front of it.

This might not be the most efficient way to do it, but it will work.

var timer = document.getElementById("timer");

var seconds = 0;
var minutes = 0;
var hours   = 0;

setInterval(function() {
    seconds++;
    if (seconds === 60) {
        seconds = 0;       // Reset seconds and increase minutes
        minutes++;
    }
    if (minutes === 60) {
        minutes = 0;       // Reset minutes and increase hours
        hours++;
    }
    if (hours === 24) {     // A day has 24 hours
        hours = 0;
    }
  
    timer.innerHTML = [
                       (hours < 10 ? "0" + hours : hours),
                       (minutes < 10 ? "0" + minutes : minutes),
                       (seconds < 10 ? "0" + seconds : seconds)
                      ].join(':');
},1);
<p id="timer"></p>
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0
var time=[0,0,0];
function increase(){
time[2]++;//secs
if(time[2]>=60){
  time[1]++;
  time[2]=0;
}
if(time[1]>=60){
  time[0]++;
  time[1]=0;
}
if(time[0]>=24){
  time[0]=0;
}
}
function show(){
 //if position has no ten digit, add a zero there, then place : between the digits
 return time.map(e=>e<10?"0"+e:e).join(":");
}

Use like this:

setInterval(increase,1000);
console.log(show());
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151