| by Arround The Web | No comments

How Can I Use setInterval and clearInterval?

setInterval” and “clearInterval” are built-in JavaScript methods. The “setInterval()” allows the execution of a function repeatedly at a specified interval. While the “clearInterval()” method stops the execution of a function that was previously started using setInterval.

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:

<span></span>
<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”:

const myInterval = setInterval(counter, 1000);

Set count to 1:

let count= 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:

function counter() {
 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:

function stopCounter() {
 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.

Share Button

Source: linuxhint.com

Leave a Reply