Home Web Front-end JS Tutorial Javascript implements analysis of product flash sale countdown (time synchronized with server time)

Javascript implements analysis of product flash sale countdown (time synchronized with server time)

Jul 03, 2018 pm 03:45 PM

This article mainly introduces the analysis of Javascript to implement product flash sale countdown (time synchronization with server time). It has certain reference value. Now I share it with you. Friends in need can refer to it

Some shopping malls often see many products doing flash sale activities, which is a countdown. This article introduces Javascript to implement product flash sale countdown (the time is synchronized with the server time). Friends who need it can learn about it

Now there is Many websites are offering flash sale products, and a very important part of this is the countdown.

Regarding the countdown, there are the following points 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. The timing starts after reading a timestamp from the server, regardless of the time-consuming network transmission:


The annotations in the figure 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 starts), the time will be longer than the actual start time of snapping (www_end, which is the time when the server countdown ends) Later (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 receiving the 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 users can count down The snap shot information sent to the server at the end was received just at the end of the server countdown:

The annotations in the picture are the same as in Pic.1 (the timeline adopts Standard time, regardless of server and page time), 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 end of the countdown time pc_start - start". However, it solves the error problem caused by the time-consuming network transmission, and the problem that the user's computer time and the server time are different. Let's continue the discussion below.

3. There must be a difference between the user's computer time and the server time, or even 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, the timing starts 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 display of time must be consistent with the logic of the program. The time deviation t obtained based on the local time and the previous step (in B).

Conclusion points:

The page starts timing when it receives the timestamp of the server response. The timing length should be minus the time taken by the entire AJAX process from sending to receiving. The timing process uses local time. To achieve (local time time offset).

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 before, how to display the server time synchronously on the page. In fact, there are several ways to achieve it. Maybe most people 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 I will give you a solution that can synchronize server time and countdown without taking up too many server resources. I will write down the implementation ideas below

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 ID)

Second step, set a calculation every second New time (the new time takes the server time as the initial value, and then adds 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: use 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. The error is basically within a few seconds. Inside, 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 show the time above) Seconds, you can also add a date. When h == 0, you can get a date or complete time directly from the server as a time correction). If you don’t understand, you can comment below and I will promptly Reply, and then follow this idea to implement a synchronized countdown. First, explain what a synchronized countdown is. It is similar to a flash sale. Set an end time, and then calculate the interval between the current time and the end time, and it must be guaranteed to be in different The countdown time displayed on the computer and the browser 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 used the countdown time interval first Calculate it uniformly into seconds, then subtract 1 second and regenerate the time format. Of course, you can also directly reduce the time according to the time synchronization example above. There are many methods. My method is not necessarily the best. Welcome everyone to communicate, thank you!

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

JSON serialization operation implemented by JS

How to solve the problem of asynchronous loading of data in vue awesome swiper bug problem

The above is the detailed content of Javascript implements analysis of product flash sale countdown (time synchronized with server time). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles