Home >Web Front-end >JS Tutorial >How Can I Dynamically Change the `setInterval` Interval During Execution?

How Can I Dynamically Change the `setInterval` Interval During Execution?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-26 18:15:11793browse

How Can I Dynamically Change the `setInterval` Interval During Execution?

Adjusting the Interval of SetInterval During Execution

Seeking a way to dynamically modify the interval of setInterval while it's running, a query emerges with a suggested approach of adjusting the interval based on a counter.

The initial attempt to use var interval = setInterval(function() { ... }, 10*counter); unfortunately yields an ineffective outcome. To achieve the desired behavior, consider employing an anonymous function:

var counter = 10;
var myFunction = function(){
    clearInterval(interval);
    counter *= 10;
    interval = setInterval(myFunction, counter);
}
var interval = setInterval(myFunction, counter);

This approach involves clearing the existing interval, updating the counter, and then setting a new interval with the adjusted interval.

An alternative suggested by A. Wolff leverages setTimeout instead of clearInterval to avoid the need for constantly clearing and resetting the interval:

var counter = 10;
var myFunction = function() {
    counter *= 10;
    setTimeout(myFunction, counter);
}
setTimeout(myFunction, counter);

The above is the detailed content of How Can I Dynamically Change the `setInterval` Interval During Execution?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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