5

I have a webservices that collects realtime market data and displays it in a web frontend.

My frontend (jQuery) needs to display a clock, somewhat synchronized with the server clock (+- a few seconds is fine).

I was thinking of delivering a UTC timestamp alongside the rest of the data the server provides when the client loads.

Then, I would start a timer and every 1 seconds increment the displayed clock.

Is this a good approach or is it better to use a time server?

Thanks!

user1094786
  • 6,402
  • 7
  • 29
  • 42

1 Answers1

12

You need to account for network latency. Data from your server won't reach you instantly. I suggest doing it using Cristian algorithm:

  1. Client marks current client time (T1) and sends request to server.
  2. Server sends it time (T2) to client.
  3. Client receives server answer and marks its current time again (T3).
  4. T3 - T1 is a total time request needed to go to the server and back (RTT). Now we can assume that going from server to client takes about half of that time. So, your "correct" time is T2 + (T3 - T1)/2

Read more about clock synchronization algorithms on wikipedia

Dmitry Osinovskiy
  • 9,999
  • 1
  • 47
  • 38