Skip to content

Instantly share code, notes, and snippets.

@jessepollak
Last active February 11, 2018 12:52
Show Gist options
  • Save jessepollak/7762987 to your computer and use it in GitHub Desktop.
Save jessepollak/7762987 to your computer and use it in GitHub Desktop.
setInterval + Immediately Invoked Function Expressions == instaInterval.
setInterval((function interval() {
// do something instantly then every 5 seconds
console.log('This is a better version of setInterval');
return interval;
})(), 5000);
@mrjoelkemp
Copy link

Nice.

@josephwegner
Copy link

Clever solution. I'm in a weirdo-javascript-hacky mood this evening, so I have two enhancements I want on this code:

  1. I want to be able to start my interval at some later point in the code.
  2. 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