0

Why my getDate function is bugging sometimes and Im getting double response in console?

https://i.stack.imgur.com/Le2Oj.jpg

here's my code

function getDate() {
    var newDate = new Date();
    var year = newDate.getFullYear();
    var month = newDate.getMonth()+1;
    var day = newDate.getDate();
    var hours = newDate.getHours();
    var minutes = newDate.getMinutes();
    var seconds = newDate.getSeconds();
    if (month < 10) {
        month = "0"+month;
    }
    if (day < 10) {
        day = "0"+day;
    }
    if (hours < 10) {
        hours = "0"+hours;
    }
    if (minutes < 10) {
        minutes = "0"+minutes;
    }
    if (seconds < 10) {
        seconds = "0"+seconds;
    }
    return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
}
setInterval(function() {
    console.log(getDate())
},1000)
kjoszi
  • 35
  • 9
  • Possible duplicate of [setInterval timing slowly drifts away from staying accurate](https://stackoverflow.com/questions/8173580/setinterval-timing-slowly-drifts-away-from-staying-accurate) – Terry Jun 29 '19 at 10:05

1 Answers1

1

Several reasons. The setInterval function doesn't always run exactly 1000 milliseconds later; after all, no clock is perfect. Also, in between each 1000 millisecond wait, the execution time of the program must be taken into account, which is probably a couple of milliseconds. As for duplicate times, if the wait is slightly less than a second, or the JavaScript date has a slight latency after the actual computer time, then duplicates can occur. The bottom line is though that on average, it will execute every 1000 milliseconds, plus the execution time of the actual function.

Oliver
  • 1,576
  • 1
  • 17
  • 31