Js中关于按钮倒计时显示(setTimeout 和 setInterval)

目标:实现一个按钮点击,同时按钮禁用并显示倒计时的js功能函数。

分析:首先要有一个按钮,绑定一个事件,这个事件功能就是定时改变按钮显示值,同时禁止按钮进行二次点击。

此功能函数需要使用js周期调用函数 setTimeout 或则 setInterval,两个方法都可以实现定时改变显示值。

setTimeout 和 setInterval的区别是什么?其实 setTimeout 和 setInterval 的最本质的区别是 触发 setTimeout 方法只执行一次,而触发 setInterval 方法只要不执行clearInterval方法是不会停止的。

解决方案

方法1:使用setTimeout方法

JS代码如下:

    <input type="button" id="btn" value="免费获取验证码" />
    <script type="text/javascript">
        //倒计时限制秒数
        var countdown = 5;
        var id;//该变量用作停止定时执行函数
        function setTime(targetElement) {
            if (countdown == 0) {
                targetElement.removeAttribute("disabled");
                targetElement.value = "免费获取验证码";
                countdown = 5;
                clearTimeout(id);//关闭定时执行函数
            } else {
                targetElement.setAttribute("disabled", true);
                targetElement.value = "重新发送(" + countdown + ")";
                countdown--;
                id = setTimeout(function () { setTime(targetElement) }, 1000);//下次定时调用setTime
            }
        }
        document.getElementById("btn").onclick = function () { setTime(this); }
    </script>

 该方法在每次改变按钮显示值后下次调用使用setTimeout方法定时调用。

方法2:使用setInterval方法

JS代码如下:

    <input type="button" id="btn" value="免费获取验证码" onclick="setTime(this)" />
    <script type="text/javascript">
        function setTime(targetElement) {
            //倒计时初始化秒数
            var countdown = 5;
            var id = setInterval(setCountdown, 1000, targetElement);
            //设置倒计时
            function setCountdown(targetElement) {
                if (countdown == 0) {
                    targetElement.removeAttribute("disabled");
                    targetElement.value = "免费获取验证码";
                    countdown = 5;
                    clearInterval(id);//停止调用函数
                } else {
                    targetElement.setAttribute("disabled", true);
                    targetElement.value = "重新发送(" + countdown + ")";
                    countdown--;
                }
            }
        }
    </script>

该方法按周期定时调用,等待时间为0的时候停止该周期调用函数。 

 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值