DEV Community

Oskar Codes
Oskar Codes

Posted on • Edited on

4 2

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".

Neon image

Set up a Neon project in seconds and connect from a Next.js application ⚡

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (1)

Collapse
 
diek profile image
diek

Mmm interesting.

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay