Reputation: 3171
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
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,
Upvotes: 3