發(fā)送短信驗證碼是網(wǎng)站或app常見的功能,為了避免用戶頻繁獲取短信驗證碼,往往會設(shè)計一個倒計時功能,當(dāng)間隔一定時間后才能再一次的獲取,下面樂信小編就來為大家介紹下如何用js實現(xiàn)發(fā)送短信驗證碼倒計時。
html部分:
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標(biāo)題文檔</title>
<style>
.wrapper{
margin-top:20px;
margin-left:20px;
}
.sns-input{
float:left;
height:28px;
}
.sns-btn{
float:left;
border-radius:5px;
margin-left:10px;
cursor:pointer;
width:80px;
height:30px;
line-height:30px;
background-color:#1f7e9a;
font-size:16px;
color:#ffffff;
text-align:center;
}
</style>
</head>
<body>
<div class="wrapper">
<input class="sns-input" id="snsCode">
<div class="sns-btn" id="snsBtn">發(fā)送</div>
</div>
<script>
var btnDisable = false; //發(fā)送按鈕是否禁用
var btn=document.getElementById("snsBtn"); //按鈕dom對象
btn.onclick=function(){ //按鈕點擊事件
//防止等待期間執(zhí)行發(fā)送
if(btnDisable){
return;
}
//1、執(zhí)行請求驗證碼邏輯
//....
//2、設(shè)置定時器進行等等
timewait(60)
//3、恢復(fù)按鈕可用
btnDisable = true;
}
function(time){
setTimeout(function(){
if(time>=0){
btn.innerHTML = time + "s后重試";
time--;
timeWait(time);
}else{
btn.innerHTML = "發(fā)送";
btnDisable = false;
}
},1000); //設(shè)置定時器
}
</script>
</body>
</html>
頁面效果:

js部分:
<script>
var btnDisable = false; //發(fā)送按鈕是否禁用
var btn=document.getElementById("snsBtn"); //按鈕dom對象
btn.onclick=function(){ //按鈕點擊事件
//防止等待期間執(zhí)行發(fā)送
if(btnDisable){
return;
}
//1、執(zhí)行請求驗證碼邏輯
//....
//2、設(shè)置定時器進行等等
timewait(60)
//3、恢復(fù)按鈕可用
btnDisable = true;
}
function(time){
setTimeout(function(){
if(time>=0){
btn.innerHTML = time + "s后重試";
time--;
timeWait(time);
}else{
btn.innerHTML = "發(fā)送";
btnDisable = false;
}
},1000); //設(shè)置定時器
}
</script>
最終實現(xiàn)效果 推薦閱讀:app短信注冊接口被刷
