Is there a way of modifying the interval of calls of function set with setInterval during runtime, other than removing it (clearInterval) and reinstating again with a different value?
Asked
Active
Viewed 1.3k times
4
-
4Nope (11+ more characters) – Ryan Kinal Feb 26 '13 at 14:03
-
See also :http://stackoverflow.com/questions/14969657/setinterval-with-exponential-time-decrease/14969792#14969792 – Ja͢ck Feb 26 '13 at 14:06
-
http://stackoverflow.com/a/29823252/1478566 – vbarbarosh Apr 23 '15 at 12:22
2 Answers
14
Use setTimeout instead, additionally this a non-blocking method for async JS:
var interval = 1000;
function callback() {
console.log( 'callback!' );
interval -= 100; // actually this will kill your browser when goes to 0, but shows the idea
setTimeout( callback, interval );
}
setTimeout( callback, interval );
Don't use setInterval
, as in some cases (lots of setInterval
+ long callbacks, which are usually longer than timeout), due to limited queue size, some callbacks will be dropped by the browser and never executed. Only setTimeout
guarantees execution.

oleq
- 15,697
- 1
- 38
- 65
3
Nope; removing the interval and re-adding it is the way to do it if you've used setInterval()
.
You could accomplish the same goal of a varying timeout, however, by calling setTimeout()
repeatedly with a variable delay at the end.
Out of curiosity, what are you doing that you want to modify the interval? Perhaps requestAnimationFrame()
might be more appropriate?

Phrogz
- 296,393
- 112
- 651
- 745
-
It's about updating a graph with changeable time scale. Larger time scale = "heavier" database request, but more sparse data points. If the plot is to display data with data points 1s apart over past 2 minutes it should update every 1s. If the user choose each data point to represent 10 minutes out of past twenty hours, there is no point to update it more frequently than once in 10 minutes. – SF. Feb 28 '13 at 10:25
-
@SF. Thanks, that's interesting and makes your goal wholly appropriate. – Phrogz Feb 28 '13 at 16:41