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
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    MooTools Clipboard Plugin

    The ability to place content into a user's clipboard can be extremely convenient for the user. Instead of clicking and dragging down what could be a lengthy document, the user can copy the contents of a specific area by a single click of a mouse.

  • By
    Drag and Drop MooTools File Uploads

    Honesty hour confession:  file uploading within the web browser sucks.  It just does.  Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms.  Add to those criticism the fact that we're all used to drag and drop operations...

Discussion

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