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??

4
  • 1
    "function executes" only appears once before "return" using the snippet you've provided. Commented Jan 2, 2017 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) Commented Jan 2, 2017 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. Commented Jan 2, 2017 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. Commented Jan 2, 2017 at 16:15

1 Answer 1

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');
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.