Home >Web Front-end >JS Tutorial >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!