JavaScript countdown timer using server time

I am trying to create a countdown timer based on server time.

Initially, I had a server on which the remaining time was installed, and simply did setTimeout for 1 second, which would reduce the time.

I found 2 problems with this:

  • The delay from the server sets the time until the client page is displayed and JavaScript starts to work. The amount of delay depends on the speed of your Internet connection and computer / JavaScript.
  • I think setTimeout by 1 second may be a little behind on slower computers.

I changed it so that the server sets the final time, and JavaScript on the client will take time (in UTC format) and calculate the remaining time remaining. This will then be executed with every setTimeout callback. This makes time and countdown perfect. If the client has a fast computer / JavaScript engine, the timer remains on the page. If the computer / JavaScript engine is slower, you can see the missed second here and there, but the time never turns off.

I found 1 problem with this method:

  • Each client cycle may be different.

Thus, the remaining time can be a couple of seconds, or 30 seconds, or even a weekend if the client time on the computer is incorrect.

Is there a way for the time remaining before the time to be accurate based on the end date of the server?

+4
source share
1 answer

I do not know what permission you need, but given the delays in the network and pages, it will be impossible to get a client-server agreement much better than a second. I would advise you to do an ajax poll every 5 or 10 seconds and adjust your timer accordingly. There is also comet , which is essentially the β€œreverse” ajax, which can cause time to the client. But in any case, you still have delays in networks and visualizers.

0
source

Source: https://habr.com/ru/post/1332688/


All Articles