javascript 倒计时工具

本文介绍了使用setTimeout结合递归实现JavaScript倒计时工具的方法,避免了setInterval的不稳定性问题。
摘要由CSDN通过智能技术生成

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值