当我点击那个向手机发送验证吗的按钮是(#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+"秒后可重新发送");
}
}
请搜索一下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+"秒后可重新发送");
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。