Last active
February 11, 2018 12:52
-
-
Save jessepollak/7762987 to your computer and use it in GitHub Desktop.
setInterval + Immediately Invoked Function Expressions == instaInterval.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setInterval((function interval() { | |
// do something instantly then every 5 seconds | |
console.log('This is a better version of setInterval'); | |
return interval; | |
})(), 5000); |
After searching the web a bit, it may actually be better to just skip setInterval altogether:
(function interval() {
// do things
console.log('This is a better version of setInterval');
setTimeout(interval, 5000);
)();
Nice.
Clever solution. I'm in a weirdo-javascript-hacky mood this evening, so I have two enhancements I want on this code:
- I want to be able to start my interval at some later point in the code.
- I don't want that
return interval;
puking out memory forever. It's nit-picky, but why not?
Here's the gross one-liner:
var interval = (function() {
return (function(f,t) {
f();
return setInterval(f,t)
})(function() {
console.log("This is an even better version of setInterval");
}, 5000)
});
And the cleaner function version:
//Or, if you don't want messy code every time, just define an instaInterval function
function instaInterval(f, t) {
return (function() {
f();
return setInterval(f, t);
});
}
//And now create executable intervals on the fly
var interval = instaInterval(function() {
console.log("This is possible the best version of setInterval");
}, 5000)
Both can be executed at any time to kick off the interval:
interval();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a clever alternative to:
Worth submitting a PR to underscore.js? I wonder if it's already in lodash.