Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!