Controlling setInterval Calls: A JavaScript Guide
When dealing with repetitive JavaScript tasks, the setInterval() function provides a convenient way to schedule functions to run at specified intervals. However, there may arise situations where you need to halt these automated calls, often triggered by user actions.
To address this, JavaScript offers a straightforward solution: the clearInterval() function. clearInterval() takes the interval ID returned by setInterval() and cancels the scheduled execution of the function.
Implementation:
To halt the execution of a function called with setInterval(), retrieve the interval ID and pass it as an argument to clearInterval(). Here's a practical example:
var refreshIntervalId = setInterval(fname, 10000); // In response to a user action to stop data refresh clearInterval(refreshIntervalId);
This code initially sets up an interval that calls fname every 10 seconds. When needed, the code stops the refresh by clearing the interval associated with the interval ID refreshIntervalId.
Additional Note:
Refer to the official documentation for setInterval() and clearInterval() for further details and examples.
The above is the detailed content of How Can I Stop `setInterval()` Calls in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!