JavaScript实现短信验证码5秒倒计时功能详解

作者:半夏

时间:2026-10-21

浏览:290

本文介绍了如何使用JavaScript实现短信验证码的5秒倒计时功能。通过对比setInterval与setTimeout的执行机制,推荐使用setTimeout递归调用来确保倒计时准确且安全。提供了完整的HTML及JS代码示例,展示如何禁用按钮、更新按钮文本并在倒计时结束后恢复发送功能。

文章目录

JavaScript实现短信验证码5秒倒计时功能详解

本文详细介绍了一种利用JavaScript实现短信验证码5秒倒计时的方法,旨在为开发者提供参考。


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>js-手机发送短信倒计时</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 ="重新发送短信";
      that.disabled = false;
      clearInterval(timer); //清除计时器
     }
    },1000);
   }
  }
 </script>
</head>
<body>
 <div class="box">
  <input type="text" id="txt">
  <button id="btn" >点击发送短信</button>
 </div>
</body>
</html> 

在实现倒计时时,可以使用setTimeout进行模拟,通常认为这种方式更为安全。当使用setInterval(fn, 1000)时,程序每隔1秒尝试执行一次,但如果每次执行耗时3秒,则实际间隔为执行时间与间隔时间的最大值。而setTimeout(fn, 1000)表示延迟1秒后仅执行一次程序;若每次执行耗时3秒,则实际总耗时为1秒加3秒,即4秒。因此,可以通过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 ="重新发送短信";
      that.disabled = false; 
     }
    }
   }
  }
 </script>

以上便是关于JavaScript实现短信验证码倒计时功能的完整内容,希望能为读者带来帮助,并欢迎大家继续支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章