本文實(shí)例講述了js實(shí)現(xiàn)倒計(jì)時(shí)重新發(fā)送短信驗(yàn)證碼功能的方法。分享給大家供大家參考,具體如下:
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>js-手機(jī)發(fā)送短信倒計(jì)時(shí)</title>  <style>    button{      width: 100px;      height: 30px;      border: none;    }    input{      outline: none;    }  </style>  <script>      window.onload = function(){      function $(id){ return document.getElementById(id); }       $('btn').onclick = function(){        clearInterval(timer); //清除計(jì)時(shí)器          var that = this;        that.disabled = true;        var count = 5;        var timer = setInterval(function(){          if(count>0){            count--;            that.innerHTML = "剩余時(shí)間"+ count +"s";          }else{            that.innerHTML ="重新發(fā)送短信";            that.disabled = false;            clearInterval(timer); //清除計(jì)時(shí)器          }        },1000);      }    }  </script></head><body>  <div class="box">    <input type="text" id="txt">    <button id="btn" >點(diǎn)擊發(fā)送短信</button>  </div></body></html> 或者使用setTimeout來(lái)模擬,一般情況下,還是推薦使用setTimeout,更安全一些。當(dāng)使用setInterval(fn,1000)時(shí),程序是間隔1s執(zhí)行一次,但是每次程序執(zhí)行是需要3s,那么就要等程序執(zhí)行完才能執(zhí)行下一次,即實(shí)際間隔時(shí)間為(間隔時(shí)間和程序執(zhí)行時(shí)間兩者的最大值)。而setTimeout(fn,1000),代表的是,延遲1s再執(zhí)行程序,且僅執(zhí)行一次。每次程序執(zhí)行是需要3s,所以實(shí)際時(shí)間為 1s+3s=4s。可以使用setTimeout遞歸調(diào)用來(lái)模擬setInterval。
<script>      window.onload = function(){      function $(id){ return document.getElementById(id); }       $('btn').onclick = function(){        var that = this;        that.disabled = true;        var count = 5;        var timer = setTimeout(fn,1000);        function fn(){          count--;          if(count>0){            that.innerHTML = "剩余時(shí)間"+ count +"s";            setTimeout(fn,1000);           }else{            that.innerHTML ="重新發(fā)送短信";            that.disabled = false;           }        }      }    }  </script>以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答