Skip to content Skip to sidebar Skip to footer

Change Interval Of Setinterval

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 val

Solution 1:

Use setTimeout instead, additionally this a non-blocking method for async JS:

var interval = 1000;

functioncallback() {
   console.log( 'callback!' );
   interval -= 100; // actually this will kill your browser when goes to 0, but shows the ideasetTimeout( 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.

Solution 2:

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?

Post a Comment for "Change Interval Of Setinterval"