js实现5秒倒计时重新发送短信功能
本文实例讲述了js实现倒计时重新发送短信验证码功能的方法。分享给大家供大家参考,具体如下:
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>js-手机发送短信倒计时</title>
<style>
button{
width:100px;
height:30px;
border:none;
}
input{
outline:none;
}
</style>
<script>
window.onload=function(){
function$(id){returndocument.getElementById(id);}
$('btn').onclick=function(){
clearInterval(timer);//清除计时器
varthat=this;
that.disabled=true;
varcount=5;
vartimer=setInterval(function(){
if(count>0){
count--;
that.innerHTML="剩余时间"+count+"s";
}else{
that.innerHTML="重新发送短信";
that.disabled=false;
clearInterval(timer);//清除计时器
}
},1000);
}
}
</script>
</head>
<body>
<divclass="box">
<inputtype="text"id="txt">
<buttonid="btn">点击发送短信</button>
</div>
</body>
</html>
或者使用setTimeout来模拟,一般情况下,还是推荐使用setTimeout,更安全一些。当使用setInterval(fn,1000)时,程序是间隔1s执行一次,但是每次程序执行是需要3s,那么就要等程序执行完才能执行下一次,即实际间隔时间为(间隔时间和程序执行时间两者的最大值)。而setTimeout(fn,1000),代表的是,延迟1s再执行程序,且仅执行一次。每次程序执行是需要3s,所以实际时间为1s+3s=4s。可以使用setTimeout递归调用来模拟setInterval。
<script>
window.onload=function(){
function$(id){returndocument.getElementById(id);}
$('btn').onclick=function(){
varthat=this;
that.disabled=true;
varcount=5;
vartimer=setTimeout(fn,1000);
functionfn(){
count--;
if(count>0){
that.innerHTML="剩余时间"+count+"s";
setTimeout(fn,1000);
}else{
that.innerHTML="重新发送短信";
that.disabled=false;
}
}
}
}
</script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。