Immediately Executing setInterval with JavaScript

By  on  

Employing setInterval for condition polling has really been useful over the years. Whether polling on the client or server sides, being reactive to specific conditions helps to improve user experience. One task I recently needed to complete required that my setInterval immediately execute and then continue executing.

The conventional and best way to immediately call a function at the beginning of a setInterval is to actually call the function before the initial setInterval` is called:

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

If you truly want to isolate the function call to the setInterval, you can use this trick of self-executing function that returns itself:

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

  // ... then return this function
  return myFunction;

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

The down side to this pattern is that it causes a maintenance issue, where the next developer doesn't understand what is going on.

Maintenance is an important part of being a good engineer, so at the very least, documentation in the form of comments or a helper function should be required. If you really want to have a self-executing setInterval, you've got it!

Recent Features

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • By
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • By
    Use Custom Missing Image Graphics Using Dojo

    A few months back I posted an article about how you can use your own "missing image" graphics when an image fails to load using MooTools and jQuery. Here's how to do the same using Dojo. The HTML We'll delegate the image to display by class...

  • By
    WebKit-Specific Style:  -webkit-appearance

    I was recently scoping out the horrid source code of the Google homepage when I noticed the "Google Search" and "I'm Feeling Lucky" buttons had a style definition I hadn't seen before:  -webkit-appearance.  The value assigned to the style was "push-button."  They are buttons so that...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!