Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning inside an IIFE function used in setInterval

setInterval( function returnval(){
  console.log('hello world');
  return returnval;
}(),2000);

First of all, keep in mind that I am new to javascript. Can someone please explain this given piece of code that is confusing me? What is actually happening when we return the function name inside an IIFE function contained inside an anonymous setInterval? And also thank you in advance.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That’s an…interesting…approach to running a function right away and then repeatedly via an interval timer. 🙂

Within a named function, the function’s name is an in-scope identifier referring to the function. So return returnval returns the function itself.

Here’s how that’s working:

  • The function expression creating it is followed by (), so it’s executed immediately, before the result is passed into setInterval. So you see "hello world" right away.
  • Then since the function returns itself, it is passed into setInterval to be set up as an interval timer.
  • A couple of seconds later, the browser calls the function again (ignoring its return value), and keeps doing that until/unless the interval timer is cancelled.

Here’s what might be a slightly clearer way to achieve the same thing (including not having the function name appear in the containing scope):

// Use a scoping function to avoid creating a symbol in the
// containing scope (there are also other ways to do this)
(() => {
    // Define it
    function returnval() {
        console.log("hello world");
    }
    // Call it immediately...
    returnval();
    // ...and also on an interval timer
    setInterval(returnval, 2000);
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading