Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Isn't time variable changing?

function getTime() {
      const d = new Date();
      const secs = d.getSeconds();
      const mins = d.getMinutes();
      const hours = d.getHours();
      
      return {
        'hours': hours,
        'mins': mins,
        'secs': secs
      }
    }
   
    let time = getTime();

    setInterval(getTime, 1000);
    setInterval(() => {
      console.log(`${time.hours}:${time.mins}:${time.secs}`);
    }, 1000);

The time displayed doesn't change. It just continually runs, outputting the same time instead of showing a change each second...

like image 906
CodeFinity Avatar asked Feb 13 '26 23:02

CodeFinity


2 Answers

time variable is declared only once, when script loads and stays in that state. Move it inside the interval to keep it updated.

function getTime() {
  const d = new Date();
  const secs = d.getSeconds();
  const mins = d.getMinutes();
  const hours = d.getHours();

  return {
    'hours': hours,
    'mins': mins,
    'secs': secs
  }
}

setInterval(() => {
  const time = getTime();
  console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
like image 177
kind user Avatar answered Feb 16 '26 13:02

kind user


You are only setting the value of time once, to the value of getTime() at that moment.

If you want the value to change, you have to set the value again every iteration.

setInterval(() => {
    var time = getTime();
    console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
like image 37
Jerodev Avatar answered Feb 16 '26 13:02

Jerodev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!