JS code in the execution of the loop event, often used in the setinterval and settimeout these two methods, the details of the two methods are not discussed in detail here, briefly share what to do when you need to stop the loop event.
(1) The SetInterval method can call a function or evaluate an expression according to the specified period (in milliseconds) and stop the method using the Clearinterval method. The specific examples are as follows:
Copy Code code as follows:
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<body>
<input type= "text" id= "clock" size= "/>"
<script language=javascript>
var int=self.setinterval ("Clock ()", 50);//Call clock () function every 50 milliseconds
function Clock () {
var t=new Date ();
document.getElementById ("Clock"). value=t;
}
</script>
<button onclick= "window.clearinterval (int)" > Stop interval</button>
</body>
Grammar Clearinterval (Id_of_setinterval)
The parameter id_of_setinterval represents the ID value returned by setinterval ().
The Clearinterval () method cancels the parameter of the Timeout;clearinterval () method set by SetInterval () must be the ID value returned by SetInterval ().
(2) The SetTimeout method is used to call a function or evaluate an expression after a specified number of milliseconds. Stop this method to use the Cleartimeout method. The specific examples are as follows:
Tip: settimeout () executes only one code at a time. If you want to call more than once, use SetInterval () or let code itself call SetTimeout () again.
Copy Code code as follows:
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<script type= "Text/javascript" >
var c=0;
var T;
function Timedcount () {
document.getElementById (' txt '). value=c;
c=c+1;
T=settimeout ("Timedcount ()", 1000);
}
function Stopcount () {
Cleartimeout (t);
}
</script>
<body>
<input type= "button" value= "Start Count" onclick= "Timedcount ()" >
<input type= "text" id= "TXT" >
<input type= "button" value= "Stop Count" onclick= "Stopcount ()" >
</body>
The Cleartimeout () method cancels the timeout set by the settimeout () method.
Grammar cleartimeout (id_of_settimeout)
The parameter id_of_setinterval represents the ID value returned by settimeout (). This value identifies the block of deferred execution code to be canceled.