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. Let’s 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. Specific examples are as follows:
Syntax clearInterval(id_of_setinterval)
The 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.
Syntax clearTimeout(id_of_settimeout)
The parameter id_of_setinterval represents the ID value returned by setTimeout(). This value identifies the deferred execution code block to be canceled.