Here is the situation..
I have a javascript frontend built with React that connects via a RESTful API to my PHP backend which handles, stores and serves all of the data. I need to be able to display the PHP Server's current time in real time (progressive ticking seconds, minutes and hours) on the client side javascript application.
I am getting the PHP server's current timestamp and sending that back with the very first request to the API.
I can display this on the frontend easily enough by using Javascript's setTime
method, but my question is how do I update this in realtime (using setInterval
) without having to query the API for a new server date every second which would be madness.
I understand and know how to display the current time with JS :
For example to display a ticking 24hr clock I would do...
setTime = () => {
this.time = new Date().toLocaleTimeString('en-US', {
hour12: false
});
this.clock.innerText = this.time;
}
componentDidMount() {
this.interval = setInterval(this.setTime, 1000);
}
... But I'm struggling to think of a way of initialising the date to the server timestamp without having to send a new Ajax request to the PHP server for the timestamp every second.
I assume there is a way to set the date only once and then start the clock ticking without having to get the new date every second but I could be wrong?