This article mainly introduces the method of stopping the execution of setInterval and setTimeout events in JavaScript. This article gives the operation example code and syntax introduction. Friends in need can refer to the following
When executing loop events in js code, The two methods setInterval and setTimeout are often used. The details of these two methods will not be discussed in detail here. I will briefly share how to operate when you need to stop the loop event.
(1) The setInterval method can call a function or calculate an expression according to a specified period (in milliseconds). To stop this method, use the clearInterval method. The specific example is as follows:
Copy code The code is as follows:
<html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <body> <input type="text" id="clock" size="50" /> <script language=javascript> var int=self.setInterval("clock()",50);//每隔 50 毫秒调用 clock() 函数 function clock(){ var t=new Date(); document.getElementById("clock").value=t; } </script> <button onclick="window.clearInterval(int)">停止 interval</button> </body> </html>
Syntax clearInterval(id_of_setinterval)
Parameter id_of_setinterval Represents the ID value returned by setInterval().
The clearInterval() method can cancel the timeout set by setInterval(); the parameter of the clearInterval() method must be the ID value returned by setInterval().
(2) The setTimeout method is used to call a function or calculate an expression after a specified number of milliseconds. This method can be stopped using the clearTimeout method. Specific examples are as follows:
Tip: setTimeout() only executes code once. If you want to call it multiple times, use setInterval() or have the code itself call setTimeout() again.
Copy code The code is as follows:
<html> <head> <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> </head> <body> <input type="button" value="开始计数" onClick="timedCount()"> <input type="text" id="txt"> <input type="button" value="停止计数" onClick="stopCount()"> </body> </html>
clearTimeout() method can be canceled by setTimeout () method to set the timeout.
Syntax clearTimeout(id_of_settimeout)
Parameter id_of_setinterval represents the ID value returned by setTimeout(). This value identifies the deferred execution code block to be canceled.
For more related articles on how to stop executing setInterval and setTimeout events in JavaScript, please pay attention to the PHP Chinese website!