Methods in JavaScript that stop the execution of setInterval and setTimeout events


The setInterval and setTimeout methods are commonly used in js code to perform circular events. The details of these methods are not discussed here, but I will briefly share how to do this when you need to stop circular events.

(1) The setInterval method can call a function or evaluate an expression for a specified period (in milliseconds), and the clearInterval method can be used to stop the method. Specific examples are 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);// every  50  Ms call  clock()  function
function clock(){
 var t=new Date();
 document.getElementById("clock").value=t;
}
</script>
<button onclick="window.clearInterval(int)"> stop  interval</button>
</body>
</html>

Grammar clearInterval (id_of_setinterval)

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

The clearInterval() method unsets timeout set by setInterval(); The arguments to the clearInterval() method 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. To stop the method, use the clearTimeout method. Specific examples are as follows:

Tip: setTimeout() executes code only once. If you make multiple calls, use setInterval() or have code itself call setTimeout() again.

<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=" Start counting " onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value=" Stop counting " onClick="stopCount()">
</body>
</html>

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

Grammar clearTimeout (id_of_settimeout)

The parameter id_of_setinterval represents the value of ID returned by setTimeout(). This value identifies the deferred execution block to cancel.