DEV Community

Oskar Codes
Oskar Codes

Posted on • Updated on

Quick JavaScript tip #1: setInterval() with modifiable delay

The JavaScript setInterval method repeatedly executes a function. It takes two parameters: the function to execute, and a delay in milliseconds between each execution. But how can that delay be changed during runtime? Let’s see.

You’re maybe thinking of using a variable as the second parameter of the setInterval method, like so:

var delay = 1000;
setInterval(myFunction, delay);

// some logic modifying the delay
Enter fullscreen mode Exit fullscreen mode

But that doesn’t work, because the setInterval method takes the value of the delay variable, and not an actual reference. So how can we make this work?

The easiest way is to set a timeout instead of an interval at the end of each execution, and pass a variable as the second parameter. That way, each time a new timeout is set the value of that variable is used, like so:

var delay = 1000;

function loop() {
  // your logic here, where you can update the delay
  setTimeout(loop, delay);
}

loop();
Enter fullscreen mode Exit fullscreen mode

Notice how we have to manually execute the loop function, which isn’t very optimized.
A possible optimization would be this:

var delay = 1000;

(function loop() {
  // your logic here, where you can update the delay
  setTimeout(loop, delay);
})();
Enter fullscreen mode Exit fullscreen mode

What I did here is to enclose the loop function inside parentheses, and then immediately execute it once using () just like a normal function. For reference, this is called an "Immediately Invoked Function Expression".

Top comments (1)

Collapse
 
diek profile image
diek

Mmm interesting.