Manos Kounelakis
Manos Kounelakis

Reputation: 3171

Get time every 1 second javascript

I have created a script that gets executed every 1 second and outputs the current hour,min and seconds in a span like this:

setInterval(()=>{
    let date = new Date();
    let time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    document.getElementById('foo').innerText = time;
}, 1000);
Time :<span id ='foo'>00:00:00</span>

As you can see every 1 second I am creating a new Date object. Is there any better way to achieve this without having to recreate the Date object every 1 second?

Upvotes: 0

Views: 1855

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97302

You can just increment the seconds of an existing Date object:

let date = new Date();

setInterval(() => {
    date.setSeconds(date.getSeconds() + 1);

    let time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    document.getElementById('foo').innerText = time;
}, 1000);

The question is, however,

  1. how much this will actually gain you in performance; and
  2. how exact the timing of the execution of the intervalled method is, and how much drift there would be over time between your calculated date and the actual date. You might want to resynchronize again, e.g. every hour or so.

Upvotes: 3

Related Questions