Home  >  Article  >  Web Front-end  >  js high-efficiency server time synchronization example

js high-efficiency server time synchronization example

小云云
小云云Original
2018-02-12 09:23:042012browse

This article mainly shares with you a js countdown function code. First, let’s talk about why server time is synchronized, 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: Go to the server to request the time every countdown


//开启定时器
var timer = setInterval(function () {  
  //执行请求,获取当前服务端时间并进行相应操作
}, 1000);

This solution is not advisable for developers with a little experience. of. 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.

Related recommendations:

js anti-refresh countdown code js countdown code

js countdown applet implementation code

js countdown snap-up example_javascript skills


The above is the detailed content of js high-efficiency server time synchronization example. 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