SoFunction
Updated on 2025-03-01

Method to stop executing setInterval and setTimeout events in JavaScript

When executing loop events in js code, two methods are often used, setInterval and setTimeout. 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 loop events.

(1) The setInterval method can call a function or calculate an expression according to the specified period (in milliseconds). Stop the method can use the clearInterval method. Specific examples are as follows:

Copy the codeThe code is as follows:

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<input type="text" size="50" />
<script language=javascript>
var int=("clock()",50);//Call the clock() function every 50 milliseconds
function clock(){
 var t=new Date();
 ("clock").value=t;
}
</script>
<button onclick="(int)">Stop interval</button>
</body>
</html>

Syntax clearInterval(id_of_setinterval)

The parameter id_of_setinterval represents the ID value returned by setInterval().

The clearInterval() method cancels the timeout set by setInterval(); the parameters 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 the specified number of milliseconds. To stop this method, use the clearTimeout method. Specific examples are as follows:

Tip: setTimeout() executes code only once. If you want to call multiple times, use setInterval() or have the code itself call setTimeout() again.

Copy the codeThe 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(){
 ('txt').value=c;
 c=c+1;
 t=setTimeout("timedCount()",1000);
}
function stopCount(){
 clearTimeout(t);
}
</script>
</head>
<body>
<input type="button" value="start counting" onClick="timedCount()">
<input type="text" >
<input type="button" value="stop counting" onClick="stopCount()">
</body>
</html>

The clearTimeout() method cancels the timeout set by the setTimeout() method.

Syntax clearTimeout(id_of_settimeout)

The parameter id_of_setinterval represents the ID value returned by setTimeout(). This value identifies the delayed execution code block to be cancelled.