This article describes the method of setting the time interval between two consecutive button clicks in JavaScript, and is shared with you for your reference. The specific implementation method is as follows:
Many times in actual applications, we may not want the button to be clicked uninterruptedly, so we have to limit a certain time interval to click the button again. Let’s introduce how to implement this function through code examples. The code is as follows:
Copy the code as follows: <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="//www.VeVB.COM/" />
<title>Wulin.com</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("It also requires"+(count)+"seconds to click");
}
}
}
</script>
</head>
<body>
<div id="thediv">0</div>
<input type="button" id="bt" value="View effect"/>
</body>
</html>
The above code implements our requirements and can limit the interval time of clicking buttons. This effect can be extended to other functions, such as limiting the interval time of posting, etc. Let’s introduce its implementation process below.
The code comments are as follows:
1.window.onload=function(){}, which specifies that the code in the function will be executed after the document content is completely loaded.
2.var odiv=document.getElementById("thediv"), obtain the div element object.
3.var obt=document.getElementById("bt"), get the button object.
4.var count=0, declare a variable and assign the initial value to 0, which is used to store the interval time.
5.var flag=null, declare a variable and assign the initial value to null, this variable is used to store the return value of the timer function.
6.function done(){}, this function can be continuously called by the timer function to decrement the count.
7.if(count==0){clearInterval(flag);}, if count==0, the execution of the timer function is stopped.
8.else{count=count-1;}, if it is not equal to 0, perform the decrement operation.
9.obt.onclick=function(){}, register the click event handling function for the button.
10.var val=parseInt(odiv.innerHTML), get the content in the div and convert it into an integer.
11.if(count==0){
odiv.innerHTML=val+1;
count=20;
flag=setInterval(done,1000);
}
If count equals 0, then +1 in the div, and set count to 20, and the execution of the timer function is turned on.
12.else{alert("It also requires"+(count)+"seconds to click");}, if count is not equal to zero, then how long does it take to click when popping up?
I hope this article will be helpful to everyone's JavaScript programming.