How to synchronize the front-end multi-terminal timing?

problem description

On the

page, starts and ends . The timing starts after clicking start and displays the timing length;
terminal 1 clicks to start, and the timing starts;
terminal 2 enters the page to obtain the time that has already started from the server, starting from the time obtained;
terminal 1 clicks to end, timing ends, and terminal 1 displays the final duration.
how does Terminal 2 know that the timing has ended and stopped, and that the final duration displayed is the same as Terminal 1?

the environmental background of the problems and what methods you have tried

now think of two options
scenario 1: front-end timer

10S;

there is a problem:

10S1210:00;210:011110:01;210:10S210:101;

Scheme 2:websocket real-time message push

121~2S

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?


May.15,2022

requests a persistent connection, disconnects manually at the end of timing, and records the time in the background.


Server pushes js script, countdown
similar

<script>count_down(500)</script>
<script>count_down(499)</script>
<script>count_down(498)</script>
// ...
<script>count_down(0)</script>

I'm a little late.

recently I have encountered similar problems. My solution is client countdown + server timing correction . The main implementation idea is:

  1. the client acquires the time from the server, calculates the difference between the acquired time and the local time, and stores the time difference as the correction benchmark .
  2. the client starts a countdown timer. The countdown timer is not a simple setInterval or setTimeout , but regularly obtains the system local time and corrects with the above correction benchmark.
  3. timer monitors the system time jump. After each jump, you need to re-obtain the server time to modify the correction benchmark.

of course, my timing accuracy is 1s , and the back end is also powerful, regardless of network delay. If you want to consider the network delay, you can listen to the onreadystatechange event, and correct the time returned by the server with the time difference between readyState = = 3 and readyState = = 4 as the delay.
of course, my application only considers keeping the time of the client and the server as consistent as possible, and to solve the problem of the subject, we need to do some article on the "stop" action: when the terminal needs to stop, it does not stop immediately, but sets the stop time at a certain time in the future, and sends this time to the other end, after this time, both ends stop together. In this way, we can try our best to ensure the consistency of the stop time on both sides .
the problem of the subject must have been solved. I hope it will be helpful to the later generations.

Menu