Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should move variables myDate and myDateFormatted to setInterval:

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

console.log({ remainingSec })
console.log({ myDateFormatted });

remainingSec = 60000 - parts.seconds * 1000;

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

  console.log({ myDateFormatted });
}, remainingSec);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading