Home > Web Front-end > JS Tutorial > Javascript implements product flash sale countdown (time synchronized with server time)_javascript skills

Javascript implements product flash sale countdown (time synchronized with server time)_javascript skills

WBOY
Release: 2016-05-16 15:39:14
Original
1902 people have browsed it

Nowadays, many websites are offering flash sale products, and a very important part of this is the countdown.

Regarding the countdown, there are a few things to note:

1. Server time should be used instead of local time (local time has problems such as different time zones and user settings).

2. Consider the time consuming of network transmission.

3. When obtaining the time, you can read it directly from the AJAX response header (obtained through getResponseHeader('Date')). The server does not need to write a special time generation script.

Process Analysis:

1. Timing starts after reading a timestamp from the server, regardless of the time it takes for network transmission:


The various annotations in the picture are (the timeline above uses standard time and has nothing to do with the time of the server and the page):

start - the time when the page item server initiates an AJAX request.

www_start - the time when the server responds to the page's request and returns a timestamp to the page.

pc_start - The time when the page receives the timestamp returned by the server and starts timing.

www_end - The time when the server countdown ends.

pc_end - The time when the page countdown ends, and it is also the time when the user clicks the button at the end of the countdown.

end - the time when the server receives the user’s click information.

It can be seen that even if the user clicks the mouse immediately at the moment the countdown ends (that is, the moment the flash sale begins), it will be later than the actual time when the snap sale starts (www_end, which is the time when the server countdown ends) ( It can be easily seen that this time difference is exactly equal to pc_start - start, which is the time it takes from the beginning of AJAX sending to the receipt of response information). If some experts use a script to send requests before the page countdown ends, other users will suffer a big loss. Therefore, we need to solve this time error problem.

2. In order to solve the problem of time error, we will shorten the page countdown time by a small amount (from the above analysis, it can be concluded that this small amount is exactly equal to pc_start - start), so that the user can send the message at the end of the countdown The snap shot message to the server was received just at the end of the server countdown:

The annotations in the picture are the same as those in Pic.1 (the timeline uses standard time and has nothing to do with the time of the server and the page). The meanings of the two new annotations are as follows:

old_pc_end——The time of pc_end without processing the network transmission time.

old_end——The end time without processing the network transmission time.

It can be seen from Pic.2 that the time error caused by the time-consuming network transmission has been completely made up. The method of making up for it is to "advance the countdown end time pc_start - start". However, it solves the error problem caused by the time-consuming network transmission, as well as the problem that the user's computer time and the server time are different. We will continue to discuss it below.

3. There must be a difference between the user's computer time and the server time, even by several time zones. How to solve this problem? The key points of the method are as follows:

A. When the page receives the timestamp www_t returned by the server, it starts timing immediately.

B. When the page receives the timestamp www_t returned by the server, it immediately calculates the time difference between the local time and the timestamp returned by the server t=new Date().getTime() - www_t*1000.

C. Still use new Date().getTime() for timing instead of using the setInterval() function (the timer is very unstable and has a large error), but the time display and program logic must be based on the local time and the time deviation t obtained in the previous step (B).

Conclusion points:

The page starts timing when it receives the timestamp of the server response. The timing should be minus the time taken by the entire AJAX process from sending to receiving. The timing process is implemented using local time (local time time deviation).

If you have any questions or suggestions, please leave a message, thank you!

Javascript tips: synchronize server time, synchronize countdown

I saw someone asking on the Internet how to display the server time synchronously on the page. In fact, there are several ways to achieve it. Most people may immediately think that they can use Ajax to request the server every second, and then get the time from the server. Displayed on the page, although this can be achieved, there is a big problem, that is, requesting the server every second, so if there are too many users, the server will crash (the memory usage will be very large), so in my case It seems that this method is not feasible. Here is a solution that can synchronize server time and countdown without taking up too many server resources. Below I will write down the implementation ideas

In the first step, when the user browses the page for the first time, the server first obtains the current time and displays it on the page (for example: displayed in the timebox span with the ID)

The second step is to set a new time to be calculated every second (the new time uses the server time as the initial value, then accumulates one second every second and generates a new time)

The third step, display the time calculated in the second step

Isn’t it very simple? It can be summed up in one sentence: take the server time as the initial value, and then automatically add one second to generate a new time on the page every second. This can ensure synchronization with the server time, and the error is basically In a few seconds, it should be okay. Let’s take a look at the implemented code:

<span id="timebox">11:21:55</span> //第一次将服务器时间显示在这里
<script type="text/javascript">
  $(function () {
    var oTime = $("#timebox");
    var ts = oTime.text().split(":", 3);
    var tnums = [parseInt(ts[0]), parseInt(ts[1]), parseInt(ts[2])];
    setInterval(function () {
      tnums = getNextTimeNumber(tnums[0], tnums[1], tnums[2]);
      showNewTime(tnums[0], tnums[1], tnums[2]);
    }, 1000);
    function showNewTime(h, m, s) {
      var timeStr = ("0" + h.toString()).substr(-2) + ":"
              + ("0" + m.toString()).substr(-2) + ":"
              + ("0" + s.toString()).substr(-2);
      oTime.text(timeStr);
    }
    function getNextTimeNumber(h, m, s) {
      if (++s == 60) {
        s = 0;
      }
      if (s == 0) {
        if (++m == 60) {
          m = 0;
        }
      }
      if (m == 0) {
        if (++h == 24) {
          h = 0;
        }
      }
      return [h, m, s];
    }
  });
</script>

Copy after login

The code is very simple and I won’t explain it here (I only display the hours, minutes and seconds above. You can also add the date. When h==0, you can get a date or complete time directly from the server. , as a time proofread), if you don’t understand, you can comment below, I will reply in time, and then follow this idea to implement a synchronized countdown. First, let me explain what a synchronized countdown is. It is similar to a flash sale, setting an end. time, and then calculate the interval between the current time and the end time, and it must ensure that the countdown time displayed on different computers and browsers is the same. The implementation code is as follows:

<!DOCTYPE html>
<html>
<head>
  <title>同步倒计时</title>
  <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
</head>
<body>
  <span id="timebox">1天00时00分12秒</span> <!--假设:1天00时00分12秒是从服务器获取的倒计时数据-->
  <script type="text/javascript">
    $(function () {
      var tid = setInterval(function () {
        var oTimebox = $("#timebox");
        var syTime = oTimebox.text();
        var totalSec = getTotalSecond(syTime) - 1;
        if (totalSec >= 0) {
          oTimebox.text(getNewSyTime(totalSec));
        } else {
          clearInterval(tid);
        }
 
      }, 1000);
 
      //根据剩余时间字符串计算出总秒数
      function getTotalSecond(timestr) {
        var reg = /\d+/g;
        var timenums = new Array();
        while ((r = reg.exec(timestr)) != null) {
          timenums.push(parseInt(r));
        }
        var second = 0, i = 0;
        if (timenums.length == 4) {
          second += timenums[0] * 24 * 3600;
          i = 1;
        }
        second += timenums[i] * 3600 + timenums[++i] * 60 + timenums[++i];
        return second;
      }
 
      //根据剩余秒数生成时间格式
      function getNewSyTime(sec) {
        var s = sec % 60;
        sec = (sec - s) / 60; //min
        var m = sec % 60;
        sec = (sec - m) / 60; //hour
        var h = sec % 24;
        var d = (sec - h) / 24;//day
        var syTimeStr = "";
        if (d > 0) {
          syTimeStr += d.toString() + "天";
        }
 
        syTimeStr += ("0" + h.toString()).substr(-2) + "时"
              + ("0" + m.toString()).substr(-2) + "分"
              + ("0" + s.toString()).substr(-2) + "秒";
 
        return syTimeStr;
      }
 
    });
  </script>
</body>
</html>
Copy after login

In order to ensure the accuracy of the countdown, I first calculated the countdown time interval into seconds, then subtracted 1 second and then regenerated the time format. Of course, you can also follow the time synchronization example above to directly reduce the time. There are many methods , mine may not be the best, everyone is welcome to communicate, thank you!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template