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 :
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 intosetInterval
. 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);
})();