Let’s first understand setInterval:
1, HTML DOM setInterval() method
Definition and usage
The setInterval() method can call functions or calculations according to the specified period (in milliseconds) expression.
The setInterval() method will keep calling the function until clearInterval() is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.
Syntax
setInterval(code,millisec[,"lang"])
Parameter Description
code Required. A function to be called or a string of code to be executed.
millisec is a must. The time interval, in milliseconds, between periodic executions or calls to code.
Return Value
A value that can be passed to Window.clearInterval() to cancel periodic execution of code.
2, HTML DOM clearInterval() method
Definition and usage
clearInterval() method can cancel the timeout set by setInterval().
The parameter of clearInterval() method must be the ID value returned by setInterval().
Syntax
clearInterval(id_of_setinterval)
Parameter Description
id_of_setinterval The ID value returned by setInterval().
How to stop:
The following example will call the clock() function every 50 milliseconds. You can also stop this clock using a button: