This time I will bring you the efficient synchronization of js with the server time. What are the precautions for synchronizing the js with the server time efficiently? 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);
Copy after login
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);
Copy after login
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:
Js Canvas makes image compression
angularJS Ionic uploads images on the mobile side (with code )
The above is the detailed content of js efficiently synchronizes time with server. For more information, please follow other related articles on the PHP Chinese website!