Home >Web Front-end >JS Tutorial >Detailed explanation of the steps for synchronizing js and server time

Detailed explanation of the steps for synchronizing js and server time

php中世界最好的语言
php中世界最好的语言Original
2018-04-17 16:44:541546browse

This time I will bring you a detailed explanation of the steps for synchronizing js and server time. What are the precautions for synchronizing js and server time? The following is a practical case, let's take a look.

Option 1: Request time from the server every countdown

//开启定时器
var timer = setInterval(function () {  
  //执行请求,获取当前服务端时间并进行相应操作
}, 1000);
This solution is known to be undesirable for developers with a little bit of experience. Because this will put unimaginable pressure on the server and cause the application to crash. If you stay on this page for one minute, the request will be sent 60 times. If 100 people are visiting this page at this time, then there will be 6,000 requests in one minute. If the number of people continues to increase, this will definitely cause unnecessary pressure on the server. And the countdown of this solution will also have a large error, because there is a delay in the request, which is also closely related to your network

status.

Option 2: Return a countdown based on server time from the server

Timestamp

//开启定时器
//假设请求获取到一个时间戳时间差 dateDiff
var timer = setInterval(function () {
  //每秒会获取本地时间,这样就算执行的周期不准确 也可以准确的获取时间差
  var countDown = endTime - (+Date.now())/1000 + dateDiff;
  // 倒计时页面渲染
}, 1000);
advantage:

Request once during the page

life cycleHigh accuracy, even if the page is open for a long time, it will still maintain high accuracy
Disadvantages:

Since the current time is obtained every second, if the local time is deliberately modified during the countdown period, the countdown will be abnormal.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

angularJS Ionic implements the mobile image upload function

BootStrap Validator operates the verification function in JS

The above is the detailed content of Detailed explanation of the steps for synchronizing js and server time. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn