开发者社区> 问答> 正文

用定时器做一个发送验证码的倒计时遇到的问题?

当我点击那个向手机发送验证吗的按钮是(#sendsms),给那个按钮加了一个disabled属性,
但是倒计时按钮还是可以点击,多次点击之后就出现问题,当curTime==0时,明明已经clearInterval(timer);了,但还是会不断进入if(curTime==0)里执行

$("#sendsms").on("click",function(){
        curTime=countTime;
        var phone=$("#form_phone").val();
        if(phone!=""){

            $("#sendsms").attr("disabled","true");
            $("#sendsms").text(curTime+"秒后可重新发送");
            timer=setInterval(handleTimer, 1000);
        }
    });

    function handleTimer(){
        if(curTime==0){
            clearInterval(timer);
            timer=null;
            $("#sendsms").removeAttr("disabled");
            $("#sendsms").text("重新发送验证码");
        }
        else{
            curTime--;
            $("#sendsms").text(curTime+"秒后可重新发送");
        }
    }

展开
收起
杨冬芳 2016-06-03 10:38:32 2123 0
1 条回答
写回答
取消 提交回答
  • IT从业

    请搜索一下setInterval方法,setInterval会创建一个异步线程,返回是这个线程的ID。

    多次点击,会创建多个线程。timer被赋值到最后一个线程的ID,停止了的也是最后一个线程。还有其他异步线程在跑着,没有停止。

    可以在handleTimer函数中打印一下timer就明白了。

    解决办法:
    1- 倒数期间,对元素解绑事件。
    2- 单一设计模式,判断timer是否被赋值。

    方法2:

    var curTime = 0,
        timer = null,
        btn = $('#button');
    btn.on('click',function(){
        if(timer === null){
            curTime = 3;
            timer = setInterval(handleTimer, 1000);
        }
    });
    function handleTimer(){
        console.log(timer);
        if(curTime === 0){
            clearInterval(timer);
            timer = null;
            btn.text('重新发送验证码');
        }else{
            btn.text(curTime + '秒后可重新发送');
            curTime --;
        }
    }

    看了一下其他答案,均在click中clearInterval清除计时器,这样的确可以修复问题,但是同时存在另外问题:
    1- 多次按下btn,多次清除定时器,性能问题。
    2- 正在倒计时的时候应该禁用掉功能函数,不应再触发重新倒计时。

    // var timer = null;
    $("#sendsms").on("click",function(){
            var phone=$("#form_phone").val();
            if(phone!="" && timer == null){
                curTime=countTime;
                $("#sendsms").attr("disabled","true");
                $("#sendsms").text(curTime+"秒后可重新发送");
                timer=setInterval(handleTimer, 1000);
            }
        });
    
        function handleTimer(){
            if(curTime==0){
                clearInterval(timer);
                timer=null;
                $("#sendsms").removeAttr("disabled");
                $("#sendsms").text("重新发送验证码");
            }
            else{
                curTime--;
                $("#sendsms").text(curTime+"秒后可重新发送");
            }
        }
    2019-07-17 19:26:12
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载