javascript 倒计时工具

JavaScript 倒计时工具

由于setInterval自身的不稳定性。因此,该工具主要是以setTimeout 结合 递归方法 来实现的,

<!--
 * @Description: 
 * @Author: HJA
 * @Date: 2019-08-31 00:17:57
 * @LastEditors: HJA
 * @LastEditTime: 2019-09-02 17:14:04
 -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Count down util</title>
</head>

<body>
  <script>
    /**
     * @params {}
     *   time: 60                              // 设置时间(S)
     *   message: "重新发送(#time#)"            // 提示模板时间占位符 #time#
     *   send: function() {}                   // Setting the method to be executed
     * }
     * @processCb {执行过程回调}
     * @finishCb  {执行完成回调}
     * @return {
     *   clear() // 停止进程,场景:同个页面中多个计时器等
     * }
     */
    function countDownUtil(params, processCb, finishCb) {
      var timeStart = 1,
        timeEnd = Number(params.time),
        timeModel = null;
      var sendCodeText = "";
      var res = {
        sendText: "",
        currentTime: timeEnd
      };
      var differenceValue = timeEnd;

      init();

      function replaceMsg() {
        return params.message.replace(/\#time\#/g, differenceValue);
      }

      function garbageCollection() {
        clearTimeout(timeModel);
        replaceMsg = null;
        init = null;
        down = null;
        res.clear = null;
      }

      function init() {

        res.sendText = replaceMsg();
        processCb(res);
        // Finish initialization and execute custom methods
        params.send && typeof params.send === "function" && params.send();
      }

      function down() {
        differenceValue = timeEnd - timeStart;
        res.sendText = replaceMsg();
        timeModel = setTimeout(function () {
          if (timeStart === timeEnd) {
            timeStart = 0;
            finishCb();
            res.clear();
          } else {
            res.currentTime = differenceValue;
            timeStart++;
            processCb(res);
            down && down();
          }
        }, 1000);
      };

      down();

      // clear
      res.clear = function () {
        garbageCollection();
      };

      return res;
    }
  </script>
  <script>
    /* demo */
    var sendTestText = "发送验证码";
    var timeTestModel = countDownUtil({
      time: 10,
      message: "重新发送(#time#)",
      send: function () {
        console.log("发送验证码");
      }
    }, function (res) {
      sendTestText = res.sendText;
      console.log(sendTestText, res);
    }, function () {
      console.log("发送验证码执行完成!");
    });
  </script>
</body>

</html>
发布了19 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/an_xinyu/article/details/100322032