javascript - 怎样让两个定时器不互相影响?
本文介绍了javascript - 怎样让两个定时器不互相影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<input class="code" onClick="TestGetCode(this)" value="获取验证码" type="button"/>
<br>
<input class="code" onClick="TestGetCode(this)" value="获取验证码" type="button"/>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
//获取短信验证码
var t=60;
function TestGetCode(i){
if(t==0){
i.removeClass("grey-bg");
i.removeAttribute("disabled");
i.value="获取短信验证码";
t=60;
}else{
i.setAttribute("disabled", true);
i.value="重新发送(" + t + ")";
t--;
$(this).addClass("grey-bg");
setTimeout(function(){TestGetCode(i)},1000);
}
}
</script>
</body>
</html>
点击其中一个还好,两个都点就出问题了
解决方案
哈哈楼主可以用setInterval啊
function TestGetCode(i){
var t = 6;
i.setAttribute("disabled", true);
i.value="重新发送(" + t + ")";
$(this).addClass("grey-bg");
var int = setInterval(function(){
i.value="重新发送(" + --t + ")";
if(t==0){
// i.removeClass("grey-bg");
i.removeAttribute("disabled");
i.value="获取短信验证码";
clearInterval(int);
}
},1000)
}
codepen http://codepen.io/Jack_Pu/pen/RRKRXJ
这篇关于javascript - 怎样让两个定时器不互相影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文