September 28, 2022

Robotic Notes

All technology News

Immediately Executing setInterval with JavaScript

2 min read

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 the 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:

setInterval(myFunction, 1000); // Every second

If you truly want to isolate the function call to the setIntervalyou 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 setIntervalyou’ve got it!

Website performance monitoring
Website performance monitoring
Website performance monitoring
Website performance monitoring
  • 5 Ways that CSS and JavaScript Interact That You May Not Know About
  • 9 Mind-Blowing Canvas Demos

    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks. Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead. Here are nine unbelievable canvas demos that …

  • MooTools ContextMenu Plugin

    MooTools ContextMenu Plugin

    ContextMenu is a highly customizable, compact context menu script written with CSS, XHTML, and the MooTools JavaScript framework. ContextMenu allows you to offer stylish, functional context menus on your website. The XHTML Menu Use a list of menu items with one link per item. The …

  • : valid,: invalid, and: required CSS Pseudo Classes

    : valid,: invalid, and: required CSS Pseudo Classes

    Let’s be honest, form validation with JavaScript can be a real bitch. On a real basic level, however, it’s not that bad. HTML5 has jumped to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching …

Source link