Thursday, September 21, 2023
HomeSoftware DevelopmentInstantly Executing setInterval with JavaScript

Instantly Executing setInterval with JavaScript


Using setInterval for situation polling has actually been helpful over time. Whether or not polling on the shopper or server sides, being reactive to particular circumstances helps to enhance consumer expertise. One process I lately wanted to finish required that my setInterval instantly execute after which proceed executing.

The traditional and finest method to instantly name a operate at the start of a setInterval is to truly name the operate earlier than the preliminary setInterval` known as:

myFunction();
setInterval(myFunction, 1000); // Each second

When you actually wish to isolate the operate name to the setInterval, you need to use this trick of self-executing operate that returns itself:

// Use a named operate ...
setInterval(operate myFunction() {
  // Do some stuff
  // ...

  // ... then return this operate
  return myFunction;

// () self-executes the operate
}(), 3000)

The down facet to this sample is that it causes a upkeep situation, the place the subsequent developer does not perceive what’s going on.

Upkeep is a crucial a part of being a superb engineer, so on the very least, documentation within the type of feedback or a helper operate needs to be required. When you actually wish to have a self-executing setInterval, you’ve got bought it!

  • CSS @supports

    Characteristic detection through JavaScript is a shopper facet finest observe and for all the proper causes, however sadly that very same performance hasn’t been out there inside CSS.  What we find yourself doing is repeating the identical properties a number of instances with every browser prefix.  Yuck.  One other factor we…

  • Create Namespaced Classes with MooTools

    MooTools has at all times gotten a little bit of grief for not inherently utilizing and standardizing namespaced-based JavaScript courses just like the Dojo Toolkit does.  Many builders create their courses as globals which is usually frowned up.  I principally disagree with that stance, however every to their very own.  In any occasion…


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments