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>
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>
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!