Diego Vega
Diego Vega

Reputation: 223

return inside javascript setTimeout

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

Upvotes: 0

Views: 538

Answers (1)

Ross Brasseaux
Ross Brasseaux

Reputation: 4150

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');
    }

Upvotes: 1

Related Questions