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

122
Visualizações
Global variables aren't updating

I've been puzzled over this for a day or two. I'm trying to create a timer, and I've extracted some of the code. I can't figure out why when I log the variable minutes or seconds, the value remains 0. It doesn't change although the variables are global variables. Many thanks!

let totalTime = 0;
let minutes = Math.floor(totalTime / 60);
let seconds = totalTime % 60;

function countTime() {
    return totalTime += 1; 
 }

 function startCount() {
    countInt = setInterval(countTime, 1000);
  }

startCount()

console.log(seconds); // Why does the output stay 0? 🤔
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would do it like this:

var totalTime = 0;
var minutes, seconds;

function startTimer(){
    let countInt = setInterval(() => {
        totalTime++;
    }, 1000);
}

function updateTimeData(){
    minutes = Math.floor(totalTime / 60);
    seconds = totalTime % 60;
}

startTimer();

setTimeout(() => {
    updateTimeData();

    console.log(seconds);
}, 5000);

The setTimeout is necessary if you want to get the right results. JavaScript is asynchronous, so the console.log in your code is being called instantly and doesn’t wait for the setInterval (because it is outside of the setInterval function).

In case you don’t know:
setTimeout works just like setInterval, but only calls once

about 4 years ago · Juan Pablo Isaza Relatório

0

In your code countTime() only runs after 1 second but the the console.log is running immediately.

Try this:

let totalTime = 0;
let minutes = Math.floor(totalTime / 60);
let seconds = totalTime % 60;

function countTime() {
    // This will run every second
    totalTime += 1;
    minutes = Math.floor(totalTime / 60);
    seconds = totalTime % 60;
    console.log(minutes, seconds); // here you log after it has been updated.
 }

 function startCount() {
    countInt = setInterval(countTime, 1000);
  }

startCount()

about 4 years ago · Juan Pablo Isaza 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