DEV Community

Oskar Codes
Oskar Codes

Posted on • Edited on

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (1)

Collapse
 
diek profile image
diek

Mmm interesting.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay