Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
How to control number display format using Javascript?

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.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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)
    }
}
over 4 years ago · Santiago Trujillo Relatório

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)
}
}

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda