0

I'm trying to figure out how this function is working depending if it's called inside a setTimeout or not.

var myFunc = function(){
    console.log('function executes');
    return function(){
       console.log('return');
    }
}

then if I call

var exe = myFunc();

it logs 'function executes' in the console

but if I call

var exe = myFunc();
setTimeout(exe,1500);

I got 'function executes' and after 1500ms 'return', but not 'function executes' again, so just the code inside the return part of the function is getting executed.

Can anyone explain this behavior??

Diego Vega
  • 223
  • 6
  • 16
  • 1
    "function executes" only appears once before "return" [using the snippet you've provided](http://jsbin.com/dupurokuma/edit?js,console). – Jonathan Lonowski Jan 02 '17 at 15:31
  • 1
    Write `var exe = myFunc;` (without parentheses) to see a different behaviour, maybe that helps you understand what happens. (What you see in the code of your question is perfectly explainable, it's the expected result) – Erich Kitzmueller Jan 02 '17 at 15:42
  • I just want to say shame on whoever down-voted this question without explanation. We're supposed to be encouraging questions like these, not discouraging them without reason. – Ross Brasseaux Jan 02 '17 at 15:58
  • The question is not bad, but could be improved by editing. The root behavior here has nothing to do with settimeout per se, but about returning a function from a function. – PMV Jan 02 '17 at 16:15

1 Answers1

1

The function myFunc is called when the variable exe is defined, which occurs on the line var exe = myFunc();. It is at that time that the line console.log('function executes'); is executed, which is why you see 'function executes' immediately in the console. The other portion of that function is to create a new function—one that will execute the line console.log('return');—and return that new function. The newly created function, since it is returned by myFunc, then becomes the definition for the variable exe.

In the next line (setTimeout(exe,1500)), you are waiting 1.5 seconds and then calling exe as a function, the definition of which should at that time be the following:

function(){
       console.log('return');
    }
Ross Brasseaux
  • 3,879
  • 1
  • 28
  • 48