This write-up will explain the use of the setInterval and clearInterval methods in JavaScript.
How to Use setInterval and clearInterval?
To use the “setInterval” and “clearInterval” methods, follow the given example.
Example
In the given example, we will create a counter that will stop on the button click by calling the “clearInterval” method to stop the function of the “setInterval” method.
Create an <span> element where the count will be shown and a button “Stop” to stop the counter increment:
<button id="refresh" onclick="stopCounter()">Stop</button>
Invoke the “setInterval” method by passing a function “counter” and time “1000” in milliseconds. Then, store the resultant value of the “setInterval” method in a variable “myInterval”:
Set count to 1:
Define a function “counter()” that will call in the “setInterval()” method. Get the reference of the <span> element and display the count by incrementing it:
document.querySelector('span').innerText= count;
count++;
}
Define another function that will trigger on the button click to stop the counter by calling the “clearInterval()” method:
clearInterval(myInterval);
}
Output
The above output indicates that the counter will stop by clicking on the button where the clearInterval() method is called which stops the counter increment in setInterval() method.
Conclusion
“setInterval” and “clearInterval” are predefined JavaScript methods that allow executing a function repeatedly with a specified time interval and stopping the execution, respectively. This write-up explained the use of the setInterval and clearInterval methods in JavaScript with a specific example. Where the counter is stopped by calling the clearInterval() method.