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!
5 HTML5 APIs You Didn’t Know Existed
When you say or read “HTML5”, you half expect exotic dancers and unicorns to walk into the room to the tune of “I’m Sexy and I Know It.” Can you blame us though? We watched the fundamental APIs stagnate for so long that a basic feature…
Chris Coyier’s Favorite CodePen Demos
David asked me if I’d be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you…
jQuery UI DatePicker: Disable Specified Days
One project I’m currently working on requires jQuery. The project also features a datepicker for requesting a visit to their location. jQuery UI’s DatePicker plugin was the natural choice and it does a really nice job. One challenge I encountered was the…
Create WordPress Page Templates with Custom Queries
One of my main goals with the redesign was to make it easier for visitors to find the information that was most popular on my site. Not to my surprise, posts about MooTools, jQuery, and CSS were at the top of the list. What…
Source link