Home >Web Front-end >JS Tutorial >js efficient server time synchronization countdown
First of all, let’s talk about why we need to synchronize server time, because there is a certain time difference between server time and local computer time. Some applications that have very high timeliness requirements, such as lottery results, cannot tolerate this kind of time difference.
Option 1: Request the time from the server every countdown
//开启定时器 var timer = setInterval(function () { //执行请求,获取当前服务端时间并进行相应操作 }, 1000);
This solution is not advisable for developers with a little 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. Moreover, 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 timestamp based on server time from the server
//开启定时器 //假设请求获取到一个时间戳时间差 dateDiff var timer = setInterval(function () { //每秒会获取本地时间,这样就算执行的周期不准确 也可以准确的获取时间差 var countDown = endTime - (+Date.now())/1000 + dateDiff; // 倒计时页面渲染 }, 1000);
Advantages:
In the page life cycle Request once in
High 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, it will Cause countdown exception.
The above is the detailed content of js efficient server time synchronization countdown. For more information, please follow other related articles on the PHP Chinese website!