Immediately Execute Initial Conditions w/SetInterval in Javascipt
I stumbled on David Welsh’s “Immediately Executing setInterval with JavaScript” blog post the other day.
IIFE for setInterval
in javascript
In particular, this struck me as interesting:
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!
Great points, David! (His blog - around since ~2007 - at one point was my go to resource for quality js tutorials + content).
Pushing the pattern
I did wonder though – can this pattern be improved (for readability’s sake, as per David’s note). As it turns out, probably! Check it:
// in js, the last item in a comma separated list is "returned"
let p = (console.log('hello!'), 5)
console.log(p)
k = setInterval((
// these will run immediately!
console.log("Hello, Wrold!"),
// more logic? ok let's have a func instead
function callMeNow() {
console.log('I will run immediately!', new Date())
}(),
// this is the last func, so it will be set as THE callback
// for setInterval
function onInterval() {
console.log('hello!', new Date())
}
), 1000)
With this approach, we end up with the following output:
> hello!
> 5
> Hello, Wrold!
> I will run immediately! Mon Jan 17 2022 22:21:44 GMT-0500 (Eastern Standard Time)
> hello! Mon Jan 17 2022 22:21:46 GMT-0500 (Eastern Standard Time)
Explanation
The long and short of it is that javascript’s ,
(comma operator) will evaluate each operand and return the final one.
We exploit this property in setInterval
which allows us to run and evaluate whatever commands we’d like before we “return” the actual setInterval
callback.
The major downside to this approach is that we cannot share a variable within this scope. But, on the upside the readability improves and the option to name functions meaninfully at least improves clarity.
Ta da! (And thank you David for all the awesome content over the years)