4

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?

SF.
  • 13,549
  • 14
  • 71
  • 107

2 Answers2

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