Home > Web Front-end > JS Tutorial > How Can I Stop `setInterval()` Calls in JavaScript?

How Can I Stop `setInterval()` Calls in JavaScript?

Patricia Arquette
Release: 2024-12-18 00:48:09
Original
688 people have browsed it

How Can I Stop `setInterval()` Calls in JavaScript?

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template