Home > Web Front-end > JS Tutorial > How Do I Stop a `setInterval()` Function in JavaScript?

How Do I Stop a `setInterval()` Function in JavaScript?

Barbara Streisand
Release: 2025-01-01 06:34:10
Original
697 people have browsed it

How Do I Stop a `setInterval()` Function in JavaScript?

How to Discontinue Scheduled Function Calls Using setInterval in JavaScript

setInterval() is a valuable tool for automating function calls at regular intervals in JavaScript. However, it's essential to know how to stop these calls when necessary. Here's how you can effectively pause the automatic execution of functions using setInterval().

The setInterval() function accepts two arguments: a function to be executed and a delay in milliseconds. The returned value is an interval ID that uniquely identifies the scheduled task. To halt the repetitive execution of this task, use the clearInterval() function.

Here's an example that demonstrates how to use setInterval() and clearInterval():

var refreshIntervalId = setInterval(functionName, 10000);

// Later on, when you want to stop the automatic function call
clearInterval(refreshIntervalId);
Copy after login

By storing the interval ID in a variable (in this example, "refreshIntervalId"), you can easily pass it to clearInterval() when you need to stop the scheduled calls.

Remember to reference the documentation for both setInterval() and clearInterval() for further details on their usage and additional features. By utilizing these functions together, you can control the execution of frequently called tasks and enhance the user experience by empowering them to stop data updates when desired.

The above is the detailed content of How Do I Stop a `setInterval()` Function 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