0

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?

spice
  • 1,442
  • 19
  • 35

1 Answers1

0

Okay after trying some things I rustled up this. It's by no means perfect and certainly wouldn't be accurate after any length of time but it's a starting point for anybody else attempting something similar.

I guess you could make an API call for the server time once every minute (not so bad) and update the timestamp variable to make it a bit more accurate. You could also add the delay for the travel and setInterval to fire to the initial timestamp too. As it stands it would be the time it takes for the API to send back the timestamp + the time it takes to get added to the call stack + rendering + the setInterval that the "displayed time" would actually be lagging by. I'm guessing probably adding 2 seconds (2000) to the timestamp timestamp = (1549149560 * 1000) + 2000; would cover it.

If anybody knows of a more accurate way to do this I'd love to hear it.

var d = null;
var timestamp = null;

function setTime() {
  timestamp = 1549149560 * 1000; // This would be the PHP timestamp * 1000
  d = new Date();
  d.setTime(timestamp);
  setInterval(updateTime, 1000);
}

function updateTime() {
  d.setSeconds(d.getSeconds() +1);
  document.getElementById('time').innerText = d;
}

setTime();
<div id="time"></div>
spice
  • 1,442
  • 19
  • 35