价格不是我们的优势,品质永远是我们的追求!
当前位置:首页行业快讯 > js实现发送短信验证码倒计时
js实现发送短信验证码倒计时
来源:动力思维乐信  时间:2018-03-27 17:15

    发送短信验证码是网站或app常见的功能,为了避免用户频繁获取短信验证码,往往会设计一个倒计时功能,当间隔一定时间后才能再一次的获取,下面乐信小编就来为大家介绍下如何用js实现发送短信验证码倒计时。

    html部分:

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</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">发送</div>
</div>

<script>
var btnDisable = false; //发送按钮是否禁用
var btn=document.getElementById("snsBtn");  //按钮dom对象
btn.onclick=function(){ //按钮点击事件
//防止等待期间执行发送
   if(btnDisable){
       return; 
   }
   //1、执行请求验证码逻辑
   //....
   //2、设置定时器进行等等
   timewait(60)
   //3、恢复按钮可用
   btnDisable = true;

}

   function(time){
       setTimeout(function(){
	       if(time>=0){
	          btn.innerHTML = time + "s后重试";
	          time--;
	          timeWait(time);
	       }else{
	          btn.innerHTML = "发送";
	          btnDisable = false;
	   
	      }
	   },1000);  //设置定时器
   }
</script>
</body>
</html>

    页面效果:

4.png

    js部分:

<script>
var btnDisable = false; //发送按钮是否禁用
var btn=document.getElementById("snsBtn");  //按钮dom对象
btn.onclick=function(){ //按钮点击事件
//防止等待期间执行发送
   if(btnDisable){
       return; 
   }
   //1、执行请求验证码逻辑
   //....
   //2、设置定时器进行等等
   timewait(60)
   //3、恢复按钮可用
   btnDisable = true;

}

   function(time){
       setTimeout(function(){
	       if(time>=0){
	          btn.innerHTML = time + "s后重试";
	          time--;
	          timeWait(time);
	       }else{
	          btn.innerHTML = "发送";
	          btnDisable = false;
	   
	      }
	   },1000);  //设置定时器
   }
</script>

    最终实现效果                推荐阅读:app短信注册接口被刷

 

3.png