Javascript to set the interval between two consecutive button clicks

  • 2020-03-30 04:13:44
  • OfStack

This article is an example of how to set the time interval between two consecutive clicks of a button in javascript. The specific implementation method is as follows:

<!DOCTYPE html> 
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="//www.jb51.net/" />
<title> The home of the script </title>
<script type="text/javascript"> 
window.onload=function(){
  var odiv=document.getElementById("thediv");
  var obt=document.getElementById("bt");
  var count=0;
  var flag=null;
  function done(){
    if(count==0){
      clearInterval(flag);
    } 
    else{
      count=count-1;
    }
  }
  obt.onclick=function(){
    var val=parseInt(odiv.innerHTML);
    if(count==0){
      odiv.innerHTML=val+1;
      count=20;
      flag=setInterval(done,1000);
    }
    else{
      alert(" You also need to "+(count)+" Seconds to click ");
    }
  }
}
</script>
</head>
<body>
<div id="thediv">0</div>
<input type="button" id="bt" value=" See the effect "/>
</body>
</html>

The above code implements our requirement that we can limit the time between button clicks. This effect can be extended to other functions, such as limiting the time between posts and so on.

Code comments are as follows:

1. Window. onload=function(){}
Var odiv= document.getelementbyid ("thediv"), gets thediv element object.
Var obt= document.getelementbyid ("bt"), gets the button object.
Var count=0, declaring a variable with an initial value of 0, which is used to store the interval.
5. Var flag=null, declaring a variable that stores the return value of the timer function and giving it an initial value of null.
Function done(){}, which can be called repeatedly by the timer function to decrement count.
7. The if (count = = 0) {clearInterval (flag); }, if count==0, the timer function is stopped.
8. The else {count = count - 1; }, if not equal to 0, do a minus operation.
9. Obt.onclick =function(){}, registers the click event handler for the button.
Var val=parseInt(odiv.innerhtml), which takes the content of the div and converts it to an integer.
11. The if (count = = 0) {
  Odiv. InnerHTML = val + 1;
  The count = 20;
  Flag = setInterval (done, 1000);
}
If the count is equal to 0, you add +1 to the div and set the count to 20 while the timer function executes.
Else {alert(" still need "+(count)+" seconds to click "); }, if count is not equal to zero, then how long is it before the popup can be clicked.


Related articles: