HomeSoftware DevelopmentInstantly Executing setInterval with JavaScript

Instantly Executing setInterval with JavaScript

Using setInterval for situation polling has actually been helpful through the years. Whether or not polling on the consumer or server sides, being reactive to particular situations helps to enhance consumer expertise. One job I not too long ago wanted to finish required that my setInterval instantly execute after which proceed executing.

The standard and greatest method to instantly name a perform originally of a setInterval is to really name the perform earlier than the preliminary setInterval` is named:

setInterval(myFunction, 1000); // Each second

Should you really wish to isolate the perform name to the setInterval, you need to use this trick of self-executing perform that returns itself:

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

  // ... then return this perform
  return myFunction;

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

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

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

  • 7 Essential JavaScript Functions

    I keep in mind the early days of JavaScript the place you wanted a easy perform for nearly every little thing as a result of the browser distributors carried out options in a different way, and never simply edge options, primary options, like addEventListener and attachEvent.  Instances have modified however there are nonetheless a number of capabilities every developer ought to…

  • From Webcam to Animated GIF: the Secret Behind!
  • Introducing MooTools ScrollSpy

    I have been excited to launch this plugin for a very long time. MooTools ScrollSpy is a singular however easy MooTools plugin that listens to web page scrolling and fires occasions primarily based on the place the consumer has scrolled to within the web page. Now you’ll be able to fireplace particular…

  • CSS Fixed Positioning

    If you wish to hold a component in the identical spot within the viewport irrespective of the place on the web page the consumer is, CSS’s fixed-positioning performance is what you want. The CSS Above we set our aspect 2% from each the highest and proper hand facet of the…



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments