Home > Enterprise >  Functions output is not updating after a minute even though it have to
Functions output is not updating after a minute even though it have to

Time:09-04

my JavaScript below is showing the current time. In this regard I want that my code is showing every new second when it is time for. when it is time for updating time the start time is displayed again in the console but not the updated time. What I am doing wrong?

 //current Date
  function formateDate(dateObject) {
     parts = {
      ms: dateObject.getMilliseconds(),
      seconds: dateObject.getSeconds(),
      minutes: dateObject.getMinutes(),
      hours: dateObject.getUTCHours()   2,
      day: dateObject.getDay(),
      date: dateObject.getDate(),
      month: dateObject.getMonth()   1,
      year: dateObject.getFullYear(),
    };
    //appending zero to Date and Month if required
    pD = parts.date < 10 ? "0"   parts.date : parts.date;
    pM = parts.month < 10 ? "0"   parts.month : parts.month;

    pHours = parts.hours < 10 ? "0"   parts.hours : parts.hours;
    pMin = parts.minutes < 10 ? "0"   parts.minutes : parts.minutes;
    
    //convert the numbers of Day into the name of weekday:
    //Array for Weekday-names
    const weekDays = [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday",
    ];

    for (let daysNumber = 0; daysNumber <= parts.day; daysNumber  ) {
      if (daysNumber === parts.day) {
        currentDayName = weekDays[daysNumber];
        break;
      }
    }
    return `${currentDayName}, ${pD}.${pM}.${parts.year} ${parts.hours}:${pMin}:${parts.seconds}:${parts.ms}`;
  }

  const myDate = new Date();
  const myDateFormatted = formateDate(myDate);
  remainingSec = 60000 - (parts.seconds * 1000);
  console.log(remainingSec)
  
 console.log(myDateFormatted)
 setInterval( () => {
     console.log(myDateFormatted)
 },remainingSec)

CodePudding user response:

You should move variables myDate and myDateFormatted to setInterval:

let myDate = new Date();
let myDateFormatted = formateDate(myDate);

console.log({ myDateFormatted });

remainingSec = 60000 - parts.seconds * 1000;

console.log({ remainingSec })

setInterval(() => {
  myDate = new Date();
  myDateFormatted = formateDate(myDate);

  console.log({ myDateFormatted });
}, remainingSec);
  • Related