Home > Web Front-end > JS Tutorial > Javascript synchronization server time and synchronization countdown tips_javascript skills

Javascript synchronization server time and synchronization countdown tips_javascript skills

WBOY
Release: 2016-05-16 15:38:04
Original
2684 people have browsed it

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 I will give you a solution that can synchronize server time and countdown without taking up too many server resources. Below I will write implementation ideas:

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

Related labels:
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