js實現5秒倒計時重新發(fā)送短信功能
更新時間:2017年02月05日 12:23:25 作者:秋天1014童話
這篇文章主要為大家詳細介紹了js實現5秒倒計時重新發(fā)送短信功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例講述了js實現倒計時重新發(fā)送短信驗證碼功能的方法。分享給大家供大家參考,具體如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js-手機發(fā)送短信倒計時</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); //清除計時器 var that = this; that.disabled = true; var count = 5; var timer = setInterval(function(){ if(count>0){ count--; that.innerHTML = "剩余時間"+ count +"s"; }else{ that.innerHTML ="重新發(fā)送短信"; that.disabled = false; clearInterval(timer); //清除計時器 } },1000); } } </script> </head> <body> <div class="box"> <input type="text" id="txt"> <button id="btn" >點擊發(fā)送短信</button> </div> </body> </html>
或者使用setTimeout來模擬,一般情況下,還是推薦使用setTimeout,更安全一些。當使用setInterval(fn,1000)時,程序是間隔1s執(zhí)行一次,但是每次程序執(zhí)行是需要3s,那么就要等程序執(zhí)行完才能執(zhí)行下一次,即實際間隔時間為(間隔時間和程序執(zhí)行時間兩者的最大值)。而setTimeout(fn,1000),代表的是,延遲1s再執(zhí)行程序,且僅執(zhí)行一次。每次程序執(zhí)行是需要3s,所以實際時間為 1s+3s=4s。可以使用setTimeout遞歸調用來模擬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 = "剩余時間"+ count +"s"; setTimeout(fn,1000); }else{ that.innerHTML ="重新發(fā)送短信"; that.disabled = false; } } } } </script>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。