2

I have a Javascript function that displays a time counter as the following : 0:0 and 0:1. But I actually want it to be displayed like this : 00:00 and 00:01.

Here is the code :

var interval = null;
var time = 0
function increaseTimer() {
    // increase and print timer
    time++
    console.log(new Date() + ' ' + 'timer: ' + parseInt(time / 60, 10) + ':' + parseInt(time % 60, 10))
    // condition of a process
    if (time % 5 == 0) {
        // some process
    }
    // stop simulation after 30s
    if (time == 30) {
        clearInterval(interval)
    }
}

I call this function with interval variable : interval = setInterval(increaseTimer, 1000)

What should I change in my code to make it work ? Thanks in advance.

EL-Mehdi Loukach
  • 732
  • 2
  • 9
  • 28
  • Does this answer your question? [How to output numbers with leading zeros in JavaScript?](https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript) – jsN00b Mar 13 '22 at 17:04
  • @jsN00b there isn't another way ? like some predefined library in js that will do the formatting ? – EL-Mehdi Loukach Mar 13 '22 at 17:13
  • How about [this one](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart)? – jsN00b Mar 13 '22 at 17:16
  • Does this answer your question? [JavaScript seconds to time string with format hh:mm:ss](https://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss) – snnsnn Mar 13 '22 at 17:18
  • @EL-MehdiLoukach see simpler code below. – Mohsen Alyafei Mar 14 '22 at 09:17

2 Answers2

2
var interval = null;
var time = 0
function increaseTimer() {
    // increase and print timer
    time++
    let prefix = parseInt(time / 60, 10)
    let postfix = parseInt(time % 60, 10)
    prefix = prefix <= 9 ? "0" + prefix.toString() : prefix.toString();
    postfix = postfix <= 9 ? "0" + postfix.toString() : postfix.toString();
    console.log(new Date() + ' ' + 'timer: ' + prefix  + ':' + postfix )
    // condition of a process
    if (time % 5 == 0) {
        // some process
    }
    // stop simulation after 30s
    if (time == 30) {
        clearInterval(interval)
    }
}
0

You can simplify the code as follows:

let interval = null,
        time = 0;
function increaseTimer() {
time++;   // increase and print timer
console.log(new Date()+' '+'timer: '+("0"+~~(time / 60)).slice(-2)+':'+("0"+time % 60).slice(-2));
if (time % 5 == 0) {   // condition of a process
    // some process
}
if (time == 30) {      // stop simulation after 30s
    clearInterval(interval)
}
}
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42