How does js ensure the same time between client and server

I"ll simplify a scenario where there is a need for a countdown to release tickets, and you need to release the ticket button on time at zero.
the question is, how do you keep this zero in sync with the server?

at present, most searches on the Internet say that when a request is sent, the result of the request is server-side time.

write down a timestamp when you request, and a timestamp when you return the server time. The time difference between the two timestamps is network time , and server time + network time is current server time .

however, there is a problem here, that is, the server time obtained is only available after the request is made, while the network time is too long, which includes the time consuming of request + response .

how to achieve millisecond error?

Jun.24,2022

there is no way. In practice, this error of less than half a second should be acceptable


I think milliseconds are beyond the range of human perception. It's basically OK to synchronize in 100 milliseconds. Anyway, the real settlement is on the server.
you can record the time difference between sending and receiving timediff

.
const currentTime = timediff/2 + serverTime

you can add a judgment. Generally, hundreds of milliseconds are acceptable. If timediff is too large, it means the network is not good. This is a problem that the client needs to solve. Make a friendly prompt to let the user switch to a better network.

Menu