Reputation: 7025
I was just getting ready to get my hands rough with Nodejs, but while experimenting and playing a bit on the first example, i found some behaviour which I am finding hard to understand.
var a = function () {
console.log('print 3');
return 5000;
};
setTimeout( function (){
console.log('print 2');
}, a()
);
console.log('print 1');
The output to the above code is:
print 3 print 1 print 2
AND a stupid doubt is, while the above code works, this one doesn't.
setTimeout( function (){
console.log('print 2');
}, (function () {console.log('print 3'); return 5000;} )
);
console.log('print 1');
Please explain the above behaviour.
Upvotes: 1
Views: 3215
Reputation: 70523
You need to call the 2nd parameter -- setTimeout expects a number
setTimeout( function (){
console.log('print 2');
}, (function () {console.log('print 3'); return 5000;} )()
);
console.log('print 1');
Upvotes: 1
Reputation: 84150
Formatting the code better should help you understand what is happening.
var a = function () {
console.log('print 3');
return 5000;
};
setTimeout( function (){
console.log('print 2'); # Executed after 5000 ms.
},
a()); # Executed first and returns 5000
console.log('print 1'); #Executed second
The following snippet does not work as you never execute the 2nd part of the function.
setTimeout( function (){
console.log('print 2');
}, (function () { # Never executed.
console.log('print 3');
return 5000;
} )
);
console.log('print 1');
The following will work:
setTimeout( function (){
console.log('print 2');
}, (function () {
console.log('print 3');
return 5000;
} )(); #The brackets () will execute the function.
);
console.log('print 1');
As an aside
The example has nothing to do with node.js and will produce the exact same results in any browser that responds to console.
Upvotes: 3
Reputation: 943515
setTimeout
takes two arguments (at least, it does the way you are using it).
The first argument is a function to call, and the second argument is the time to delay before calling it.
In your first example, you pass a anonymous function and a Number (the return value of a()
).
In your second example, you pass two anonymous functions (because you never call the second function (there is no ()
)).
setTimeout(
function (){
console.log('print 2');
},
(function () {console.log('print 3'); return 5000;})()
);
console.log('print 1');
Upvotes: 1