I am executing setInterval(myFunction, 10000);
to invoke a function every 10 seconds in JavaScript. Can this repeated execution be terminated based on a specific event? I aim to give users the ability to stop the continuous data refresh.
To halt the execution of a setInterval
in JavaScript, you can employ the clearInterval
method. This function stops the ongoing interval when you call it using the interval’s ID, which is returned by setInterval
. Here’s a practical example:
// Start setInterval and store its ID
const intervalId = setInterval(myFunction, 10000);
// Function to stop the interval
function stopInterval() {
clearInterval(intervalId);
}
// Assuming there's a button to stop the interval
const stopButton = document.getElementById('stopButton');
// Link the function to a button or event
stopButton.addEventListener('click', stopInterval);
In this example, setInterval
starts the repeated execution of myFunction
every 10 seconds. The intervalId
is used by clearInterval
to halt the process. The interval is stopped when the user clicks a button identified by ‘stopButton’
. You can tailor this to stop on any event by replacing the event listener.