js realizes 5 second countdown to resend short messages

  • 2021-07-16 01:25:26
  • OfStack

In this paper, an example is given to describe the method of js to realize the function of resending SMS verification code in countdown. Share it for your reference, as follows:


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>js- Countdown of sending short messages by mobile phone </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); // Clear the timer  
    var that = this;
    that.disabled = true;
    var count = 5;
    var timer = setInterval(function(){
     if(count>0){
      count--;
      that.innerHTML = " Remaining time "+ count +"s";
     }else{
      that.innerHTML =" Send a text message again ";
      that.disabled = false;
      clearInterval(timer); // Clear the timer 
     }
    },1000);
   }
  }
 </script>
</head>
<body>
 <div class="box">
  <input type="text" id="txt">
  <button id="btn" > Click Send SMS </button>
 </div>
</body>
</html> 

Or use setTimeout to simulate. In general, it is recommended to use setTimeout, which is safer. When using setInterval (fn, 1000), the program is executed once at an interval of 1s, but each program execution requires 3s, so it is necessary to wait until the program is executed before executing the next time, that is, the actual interval time is (the maximum of both interval time and program execution time). setTimeout (fn, 1000) means that the program is delayed by 1s and executed only once. 3s is required for each program execution, so the actual time is 1s+3s=4s. setTimeout recursive calls can be used to simulate 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 = " Remaining time "+ count +"s";
      setTimeout(fn,1000); 
     }else{
      that.innerHTML =" Send a text message again ";
      that.disabled = false; 
     }
    }
   }
  }
 </script>

Related articles: