Convert stopwatch to hh mm ss format

Asked

Viewed 57 times

-1

My stopwatch is running without format 00:00:00

I created a div in index.html

<!-- TIMER -->
<div class="container">
  <span id="display">00:00:00</span>
</div>

No js

static iniciarTimer() {
        let time = 0
        const timer = document.getElementById(ID_DISPLAY)
        // atualizar o texto a cada segundo
        const atualizarTexto = () =>
        
        (timer.innerHTML =  time++)

        atualizarTexto()
        
        const idDoDisplay = setInterval(atualizarTexto, 1000)
        return idDoDisplay
    }

And start it in another file: main using this.tela.iniciarTimer()

It rotates but without the standard (00:00:00). What should I add, remove or improve?

  • Need to make some ifs to verify. Here have an example

  • I took a look, and I made this code but when leaving the screen it pauses the count.

  • That would be another question. In that have examples in PHP, if you want in Javascript even, with cache, I recommend first try to do and, if not able, create a new question presenting its difficulties.

3 answers

2

Create an object of the type Date and with the method Date.prototype.setHours() adjust your time, minutes, second and milliseconds by 0. The respective portion the date in this case is irrelevant.
Within its function atualizarTexto() increment by one second (1000 milliseconds) this object of type Date with Date.prototype.setTime() and with the method Date.prototype.toLocaleTimeString() get a string with a language-sensitive representation of a portion of that instance of Date.

function iniciarTimer() {
  const timer = document.getElementById("display");
  let time = new Date();                            //Inicializa objeto Date para ser usado como cronômetro.
  time.setHours(0, 0, 0, 0);                        //Reseta o cronômetro.
  const atualizarTexto = function() {
    time.setTime(time.getTime() + 1000);            //Incrementa o cronômetro em  1s.
    timer.innerHTML = time.toLocaleTimeString('pt-BR', {
      hour: "2-digit",                              //Exibirá horas.
      minute: "2-digit",                            //Exibirá minutos.
      second: "2-digit"                             //Exibirá segundos.
    });
  };
  return setInterval(atualizarTexto, 1000);
}

iniciarTimer();                                     //Inicializa o time para ser exibido aqui no exemplo.
<!-- TIMER -->
<div class="container">
  <span id="display">00:00:00</span>
</div>

  • 1

    Show! This code is cleaner and easier to understand. I used and ran everything right.

1

Reviewing the codes I arrived at a solution, leaving in this way:

static cronometro () {
        let timer = document.getElementById(ID_DISPLAY)
        let timerArray = timer.textContent.split(':')
        let timerParado = true
        let [hh, mm, ss] = timerArray

        setInterval(() => {
            if(timerParado) {
                timerParado = false
            }
                ss = parseInt(ss) + 1
                timer.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`
            if (parseInt(ss) > 59 ) {
                ss = '00'
                mm = parseInt(mm) + 1
                timer.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`
            }
            else if (parseInt(mm) > 59 ) {
                mm = '00'
                hh = parseInt(hh) + 1
                timer.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}:${String(ss).padStart(2, '0')}`
            }
        }, 1000);

    }

1

Another way to follow your line of code would be to organize your team in time, minute and second, and then format...

 function iniciarTimer() {
      let hora = 0
      let minuto = 0
      let seg = 0
      const timer = document.getElementById('display')
      // atualizar o texto a cada segundo
      const atualizarTexto = ()=>{
       timer.innerHTML = formata_numero(hora) + " : " + formata_numero(minuto) + " : " + formata_numero(seg);
          seg++; //incrementa segundos
          if (seg == 60) {
            minuto ++; //incrementa minutos a cada 60 segundos
            seg = 0;
            if (minuto == 60) {
              minuto = 0;
              hora++;//incrementa horas a cada 60 minutos
            }
          }
      }

      atualizarTexto()

      const idDoDisplay = setInterval(atualizarTexto, 1000); //set 10 para teste, porem 1000 deve ser setado para incrementar de 1 em 1 segundo
      return idDoDisplay
}
iniciarTimer();

//concatena o ZERO caso numero seja menor que 10
function formata_numero( num ){
  return (num < 10)?"0" + num:num;
}
<!-- TIMER -->
<div class="container">
  <span id="display">00:00:00</span>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.