Immediately Executing setInterval with JavaScript
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!
Contents
Being a Dev Dad
I get asked loads of questions every day but I’m always surprised that they’re rarely questions about code or even tech — many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes…
I’m an Impostor
This is the hardest thing I’ve ever had to write, much less admit to myself. I’ve written resignation letters from jobs I’ve loved, I’ve ended relationships, I’ve failed at a host of tasks, and let myself down in my life. All of those feelings were very…
MooTools Zebra Table Plugin
I released my first MooTools class over a year ago. It was a really minimalistic approach to zebra tables and a great first class to write. I took some time to update and improve the class. The XHTML You may have as many tables as…
Highlighter: A MooTools Search & Highlight Plugin
Searching within the page is a major browser functionality, but what if we could code a search box in JavaScript that would do the same thing? I set out to do that using MooTools and ended up with a pretty decent solution. The MooTools JavaScript Class The…
[ad_2]
Source link