The setInterval() Method is used to repeatedly call some function after a specified amount of time. It is commonly used to set a delay for functions that are executed repeatedly like animated pictures. The setInterval() Method returns a unique ID with which the timer can be canceled at a later time.
When you click the above button, the setInterval method call the function and start execute. It will continuously alert with 4000 milliseconds interwel.
Stop setInterval() method
If you want to stop the execution of setInterval() method, call clearInterval() method and just pass the interval ID returned by the setInterval() method.
It is commonly used if you wish to have your function called once after the specified delay. That is, it will be run a specified number of milliseconds from when the setTimeout() method was called. The setTimeout() Method returns a unique ID with which the timer can be canceled at a later time.
When you click the above button, it alert only one time.
How to Stop the setTimeout()
If You want to stop the execution of setTimeout() method, call clearTimeout() method and just pass the timeout ID returned by the setTimeout() method.
The setInterval() and setTimeout() methods are from HTML DOM Window object. The main difference is that setTimeout() triggers only once, and setInterval() keeps on triggering repeatedly unless you call it to stop.