A
A
AE422021-08-11 14:25:57
JavaScript
AE42, 2021-08-11 14:25:57

How to synchronize time between server and frontend?

I have a server that gives the date new Date() + 20 seconds (2021-08-11T07:18: 38.085Z
)

on the timer

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim, 2021-08-11
@AE42

Let the server send not a date, but the number of seconds before the time expires.
And on the client, run setInterval every 1000ms. (1s)
Profit (almost).
Ps why almost:
1) the callback will fire after 1000ms only if the document stream is not blocked by other heavy synchronous calculations.
2) browsers, chrome in particular, can optimize timer ticks if the user left the tab (switched to another or minimized the browser). Thus, it will tick not every 1000ms, but less often. I have not seen this, but it may not tick at all.
In my experience - within a few minutes, if you minimize the browser, the timer started to lag by a few seconds.

A
Armenian Radio, 2021-08-11
@gbg

I suspect some crutches aka XY problem .
Protection against cheating by the user of time can only be a check on the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question